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
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
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
сообщение об ошибке:
код:
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
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
__________________
0 |
epyskop 143 / 130 / 30 Регистрация: 26.07.2017 Сообщений: 633 |
||||
13.07.2020, 20:05 |
2 |
|||
У вас же target уже Transform, зачем вы вновь ей пишете
У вас там ничего не подсвечивается в редакторе кода?
0 |
247 / 173 / 75 Регистрация: 04.07.2012 Сообщений: 711 |
|
14.07.2020, 15:58 |
3 |
А всё потому, что в соседней теме пользователь с ником samana сказал убрать большую букву в слове transform… офф топ:
0 |