Error cs0103 unity

I have a generic class like this: public class Connection where T: Stream { protected T _stream; protected TcpClient _client; public void Connect(){/*Do somthing*/} public

I have a generic class like this:

public class Connection<T> where T: Stream 
{
    protected T _stream;
    protected TcpClient _client;

    public void Connect(){/*Do somthing*/}
    public void Disconnect(){/*Do somthing*/}

    public void Reconnect()
    {
        Disconnect();
        Connect();
    }
}

I use VisualStudio as editor, it has no error but in unity editor console it says:

error CS0103: The name ‘Disconnect’ does not exist in the current context

and

error CS0103: The name ‘Connect’ does not exist in the current context

The line of the error is in the Reconnect() function.

If I remove generic from this class, it hasn’t any error.
Is this a bug or I missed somthing?

asked Dec 25, 2016 at 23:06

M6stafa's user avatar

M6stafaM6stafa

1232 silver badges12 bronze badges

7

I fix it like this:

public abstract class BaseConnection<T>
{
    protected T _stream;
    protected TcpClient _client;

    public abstract void Connect();
    public abstract void Disconnect();
}

public class Connection<T> : BaseConnection<T> 
    where T: Stream 
{
    public override void Connect(){/*Do somthing*/}
    public override void Disconnect(){/*Do somthing*/}

    public void Reconnect()
    {
        Disconnect();
        Connect();
    }
}

answered Jan 4, 2017 at 11:10

M6stafa's user avatar

M6stafaM6stafa

1232 silver badges12 bronze badges

Скрипт не работает

Скрипт не работает

Вот такой простенький скрипт но консоль выдает данную ошибку=Assets/M2.cs(8,20): error CS0103: The name `col’ does not exist in the current context
И еще желтую ошибку=Assets/M2.cs(10,28): warning CS0219: The variable `rotationY’ is assigned but its value is never used

Используется csharp

using System.Collections;

public class Moving2 : MonoBehaviour {

       
        void Update ()
        {          
                if(col.gameObject.name == «RollerBall»)
                {
                Quaternion rotationY = Quaternion.AngleAxis (180, Vector3.up);

                       
                }
        }
}

developers
UNец
 
Сообщения: 15
Зарегистрирован: 30 янв 2016, 22:55

Re: Скрипт не работает

Сообщение Smouk 03 мар 2016, 10:36

1. Из этого не понять в чем именно ошибка. Где объявлено col и зачем? Для получения имени объекта если скрипт висит на нем это не нужно.
В принципе не очень верно каждый update без необходимости сравнивать текст. Лучше при создании объекта использовать флаг или int с типом объекта, например.
2. Если перевести там прямо написано, что переменная rotationY никогда не используется.

Последний раз редактировалось Smouk 03 мар 2016, 10:39, всего редактировалось 2 раз(а).

Smouk
UNIт
 
Сообщения: 146
Зарегистрирован: 16 сен 2009, 08:47

Re: Скрипт не работает

Сообщение BladeBloodShot 03 мар 2016, 10:38

Ну так переведи ошибки, нет определения col то бишь надо public var col = там чему то;

BladeBloodShot
UNец
 
Сообщения: 38
Зарегистрирован: 03 фев 2016, 22:31



Re: Скрипт не работает

Сообщение developers 03 мар 2016, 12:06

А насчет 2 причины

developers
UNец
 
Сообщения: 15
Зарегистрирован: 30 янв 2016, 22:55

Re: Скрипт не работает

Сообщение iLLoren 03 мар 2016, 13:59

developers писал(а):А насчет 2 причины

Научись разбираться с мелочами самостоятельно, тебе самому то не стыдно что имея видео о том как с 0 сделать всё правильно ты косячишь и вместо пересмотров урока ты плачешь на форуме о проблемах которые сам можешь легко решить?

Аватара пользователя
iLLoren
UNIт
 
Сообщения: 103
Зарегистрирован: 31 дек 2015, 12:00

Re: Скрипт не работает

Сообщение Tolking 03 мар 2016, 14:16

Желтая ошибка называется предупреждением и в переводе с английского гласит: ты нахрена опредилил переменную `rotationY’ если нигде ее не используешь!

Таки да!!! Английский знать надо или пользоваться переводчиком…

Ковчег построил любитель, профессионалы построили Титаник.

Аватара пользователя
Tolking
Адепт
 
Сообщения: 2684
Зарегистрирован: 08 июн 2009, 18:22
Откуда: Тула


Вернуться в Скрипты

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 6



сообщение об ошибке:
5f91cfa10feb2334483924.png
код:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using UnityEngine;
using UnityEngine.UI;

public class BattleController : MonoBehaviour
{
    // Параметры очереди, игрока и противника, а также их отображения
    public int PL_HP = 200;
    public float PL_Magic = 500;
    public int Enemy_HP = 180;
    public float Reduction_of_Magic = 1;
    public Text Enemy_HP_Display;
    public Text PL_HP_Display;
    public Text PL_Magic_Display;
    public bool Bot_Turn = false;
    private static System.Random rnd = new System.Random();
    private int Delay = rnd.Next(0, 3);
    private float Rdn = rdn.Next(1.9, 2.0);
    //очередь компьютера
    void Update()
    {
        if (Bot_Turn = true)
        {
            if (!(Rnd = 1.9))
            {
                PL_HP = PL_HP - 35;
            }
            else
            {
                PL_HP = PL_HP - 20;
            }
        }
    }
    //восстановление магии игрока(закончить позже)
    private void FixedUpdate()
    {
        
    }
    // атаки игрока
    public void PL_Attack1()
    {
        if (Bot_Turn = false & PL_Magic > 20)
        {
            Enemy_HP = Enemy_HP - 25;
            PL_Magic = PL_Magic - 20;
            Bot_Turn = true;
        }
    }
    public void PL_Attack2()
    {
        if (Bot_Turn = false & PL_Magic > 32)
        {
            Enemy_HP = Enemy_HP - 40;
            PL_Magic = PL_Magic - 32;
            Bot_Turn = true;
        }
    }
}

Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

In my PlayerMovement.cs I get this error with MonoBehaviour, Animator, playerAnimator, Vector3, Rigidbody, and Qauternion. Here is a copy of my file:

using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {

    private Animator playerAnimator;
    private float moveHorizontal;
    private float moveVertical;
    private Vector3 movement;
    private float turningSpeed = 20f;
    private Rigidbody playerRigidbody;

    // Use this for initialization
    void Start () {

        // Gather components from the play GameObject
        playerAnimator = GetComponent<Animator> ();
        playerRigidbody = GetComponent<Rigidbody> ();

    }

    // Update is called once per frame
    void Update () {

        // Gather input from the keyboard
        moveHorizontal = Input.GetAxisRaw ("Horizontal");
        moveVertical = Input.GetAxisRaw ("Vertical");

        movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

    }

    void FixedUpdate () {

        // If the player's movement vector does not equal zero...
        if (movement != Vector3.zero) {

            // ...then create a target rotation based on the movement vecor...
            Quaternion targetRotation = Quaternion.LookRotation(movement, Vector3.up);

            // ...and create another rotation that moves from the current roatation to the target rotation...
            Quaternion newRotation = Qauternion.Lerp (playerRigidbody.rotation, targetRotation, turningSpeed * Time.deltaTime);

            // ...and change the player's rotation to thenew incremental rotation...
            playRotation.MoveRotation(newRotation);

            // ...then play the animation.
            playerAnimator.SetFloat ("Speed", 3f);
        } else {
            //Otherwise don't play the animation
            playerAnimator.SetFloat ("Speed", 0f);
        }

    }

}

Any help would be greatly appreciated. Thank you!

2 Answers

Alan Mattanó

PLUS

Go to the Console by pressing Ctrl Shift «C» or in the top menu: Windows -> Console .
The Console will show you the Error message with the file location «Assets/Path/FileName.cs»
and the line number, where is the error. In your case is can be 103 then there is a coma and the position.
If you double click the error message in the console, Unity will try to open Mono putting the cursor at the same position where is the error. It can be shown in red. The error can be not in the same line, for example if we forget to close a ;
or }. In this case look line above the error.
The console will show you more than one error probably as consequence of the first one. So if you fix the first error, the other errors messages probably will disappear.

Becky Hirsch September 15, 2015 12:24am

Great to know! Thanks again Alan! :)

Laurean

0 / 0 / 0

Регистрация: 08.07.2020

Сообщений: 3

1

13.07.2020, 19:55. Показов 5045. Ответов 2

Метки нет (Все метки)


Unity ошибка error CS 0103: The name ‘target’ does not exist in the current context
скрипт

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class EnemyAI : MonoBehaviour
{
public float SeeDistance;
public float AttackDistance;
public float Speed;
private Transform Target;
// Use this for initialization
void Start()
{
target = GameObject.FindWithTag("Player 1").transform;
}
 
// Update is called once per frame
void Update()
{
if (Vector3.Distance(transform.positon, target.transform.positon) < SeeDistance)
{
if (Vector3.Distance(transform.positon, target.transform.positon) > SeeDistance)
{
transform.LookAt(target.transform);
transform.Translate(new Vector3(0, 0, speed = Time.deltaTime));
}
}
}
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



epyskop

143 / 130 / 30

Регистрация: 26.07.2017

Сообщений: 633

13.07.2020, 20:05

2

У вас же target уже Transform, зачем вы вновь ей пишете

C#
1
target.transform.positon

У вас там ничего не подсвечивается в редакторе кода?



0



247 / 173 / 75

Регистрация: 04.07.2012

Сообщений: 711

14.07.2020, 15:58

3

А всё потому, что в соседней теме пользователь с ником samana сказал убрать большую букву в слове transform…
Автор темы решил заодно и Target с маленькой написать…

офф топ:
«- Бананы! Ананы!
— Правильно: Ананасы.
— Ананасы! Бананасы!»



0



Понравилась статья? Поделить с друзьями:
  • Error cs0103 the name input does not exist in the current context
  • Error cs0103 the name facingright does not exist in the current context
  • Error cs0103 the name convert does not exist in the current context
  • Error cs0103 the name console does not exist in the current context
  • Error cs0101 unity