Ошибка cs0103 unity

Вот такой простенький скрипт но консоль выдает данную ошибку=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

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

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

Вот такой простенький скрипт но консоль выдает данную ошибку=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
Откуда: Тула


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

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

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



Laurean

0 / 0 / 0

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

Сообщений: 3

1

13.07.2020, 19:55. Показов 5155. Ответов 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



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! :)

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Ошибка cs0029 юнити
  • Ошибка cs0004 pubg на ps5
  • Ошибка crystal process died
  • Ошибка cryptopro уц не является доверенным
  • Ошибка cryengine error sniper ghost warrior contracts

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии