Unity error cs0201

Using Unity, I'm trying to add GameObjects with a particular script to an array. I've tried a bunch of different methods and ultimately I've ended up with this, and for the life of me I can't find ...

Using Unity, I’m trying to add GameObjects with a particular script to an array. I’ve tried a bunch of different methods and ultimately I’ve ended up with this, and for the life of me I can’t find why it’s giving me the error, because everything I’ve googled for the last hour has said it’s mostly from syntax and I cannot find the syntax error. I wonder if it wouldn’t just make sense to use a get/set but I really don’t understand how those are different from for loops. Thank you!

public class QuestFinderScript : MonoBehaviour {
GameObject[] objects;
public List<GameObject> interactables = new List<GameObject> ();
int interactablesSize;

void Start(){

    interactables = new List<GameObject> ();
    objects = GameObject.FindGameObjectsWithTag ("Untagged");
    interactablesSize = objects.Length;

    for (int i = 0; i < interactablesSize; i++) {

        InteractionSettings iset = objects [i].GetComponent<InteractionSettings> ();
        if (iset != null) {
            interactables.Add [i];

        }
    }
}

}

asked Feb 23, 2017 at 20:19

jannar's user avatar

4

Thanks to your input, I’ve fixed it — part of the problem was that I didn’t realize the script I was referencing was a child, not a component of the gameobject itself. But if anyone’s curious:

    interactables = new List<GameObject> ();
    objects = GameObject.FindGameObjectsWithTag ("questable");
    interactablesSize = objects.Length;

    Debug.Log (interactablesSize);

    for (int i = 0; i < interactablesSize; i++) {

        InteractionSettings iset = objects [i].GetComponentInChildren<InteractionSettings> ();
        if (iset != null) {
            interactables.Add(iset.gameObject);
        }
    }

answered Feb 23, 2017 at 20:40

jannar's user avatar

jannarjannar

511 gold badge1 silver badge4 bronze badges

1st problem: As Pogrammer says, Add is a function for list, not an indexer.

Add(i) is correct

Of course, the error is due to your 1st problem.

2nd problem: Interactables os list of GameObject, you try to add integer(i is integer) to list of GameObjects.

Review your code and understand what you are going to add to Interactables.

answered Feb 23, 2017 at 20:32

Efe's user avatar

EfeEfe

78010 silver badges32 bronze badges

Эдис

0 / 0 / 0

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

Сообщений: 14

1

19.06.2019, 21:47. Показов 4644. Ответов 14

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


Привет.
У меня выходят следующие ошибки :
1. Assets/Scripts/HealthHelper.cs(25,33): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
2. Assets/Scripts/HealthHelper.cs(28,32): error CS1023: An embedded statement may not be a declaration or labeled statement
Я не пойму в чем дело?!

Вот мой код :

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
30
31
32
using UnityEngine;
using System.Collections;
 
public class HealthHelper : MonoBehaviour 
{
    public int MaxHelper = 100;
    public int Helper = 100;
 
    // Use this for initialization
    void Start () {
    
    }
    
    // Update is called once per frame
    void Update () {
    
    }
 
    public void GetHit(int damage) 
    {
        int health = HealthHelper - damage;
 
        if (health <= 0) 
        (
                Destroy(gameObject)
        )
 
        Health = health;
        Debug.Log("Health = " + Health);
 
    }
}

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



0



Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

19.06.2019, 21:47

Ответы с готовыми решениями:

CS0201
Ругается на else

double x = Convert.ToDouble(Console.ReadLine());…

Ошибки в проекте
Здравствуйте, пишу программу для решение уравнения методом Виета-Кардано.
Вот у меня главный…

Ошибки в проекте
Вот несколько ошибок в проекте(которые выдаются, когда уже проект собрался, и идет стадия Linker)

Ошибки в проекте
добрый день, помогите исправить ошибки, делал по методическим указаниям (прилогается в архиве) есть…

14

1max1

3088 / 1617 / 921

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

Сообщений: 4,620

19.06.2019, 22:38

2

C#
1
HealthHelper - damage

Ты от класса HealthHelper отнимаешь int ><

C#
1
Health = health;

Необъявленная переменная.



1



Эдис

0 / 0 / 0

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

Сообщений: 14

20.06.2019, 06:22

 [ТС]

3

Цитата
Сообщение от 1max1
Посмотреть сообщение

C#
1
HealthHelper - damage

Ты от класса HealthHelper отнимаешь int ><

C#
1
Health = health;

Необъявленная переменная.

Но у меня вё же выходят ошибки.
Я хочу , чтобы у персонажа отнималось здоровье — 10
Я делал по этому видео:

У меня стало не получаться с этим кодом, с 21:30 минуты.
Когда он начал писать этот код.



0



1max1

3088 / 1617 / 921

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

Сообщений: 4,620

20.06.2019, 09:18

4

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
30
using UnityEngine;
using System.Collections;
 
public class HealthHelper : MonoBehaviour 
{
    public int MaxHealth = 100;
    public int Health = 100;
 
    // Use this for initialization
    void Start () {
    
    }
    
    // Update is called once per frame
    void Update () {
    
    }
 
    public void GetHit(int damage) 
    {
        int health = Health - damage;
 
        if (health <= 0) 
        {
            Destroy(gameObject)
        }
 
        Health = health; 
    }
}



1



Эдис

0 / 0 / 0

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

Сообщений: 14

20.06.2019, 16:29

 [ТС]

5

И после этого у меня это появилось:
1. Assets/Scripts/HealthHelper.cs(26,17): error CS1525: Unexpected symbol `}’
2. Assets/Scripts/HealthHelper.cs(31,1): error CS8025: Parsing error

мой код:

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
30
using UnityEngine;
using System.Collections;
 
public class HealthHelper : MonoBehaviour 
{
    public int MaxHealth = 100;
    public int Health = 100;
    
    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update () {
        
    }
    
    public void GetHit(int damage) 
    {
        int health = Health - damage;
        
        if (health <= 0) 
        {
            Destroy(gameObject)
        }
        
        Health = health; 
    }
}



0



2502 / 1515 / 806

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

Сообщений: 3,701

20.06.2019, 17:10

6

Лучший ответ Сообщение было отмечено Эдис как решение

Решение

После Destroy(gameObject) не хватает точки с запятой.



0



Эксперт .NET

6270 / 3898 / 1567

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

Сообщений: 9,190

20.06.2019, 17:20

7

Кому-то стоило бы сначала изучить C# на базовом уровне, прежде чем лезть в Unity…



0



3088 / 1617 / 921

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

Сообщений: 4,620

20.06.2019, 18:47

8

Да промахнулся я немного, писал от руки.



0



Эдис

0 / 0 / 0

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

Сообщений: 14

20.06.2019, 21:52

 [ТС]

9

Цитата
Сообщение от samana
Посмотреть сообщение

После Destroy(gameObject) не хватает точки с запятой.

И всё?

Добавлено через 7 минут
Спасибо всё сработало)))

Добавлено через 1 час 13 минут
Снова , здравствуйте!
У меня вышла ошибка, когда я хотел добавить монеты в игру за убивание монстра будут доваться они.
Но выходит ошибка.
Вот она:
Assets/Scripts/GameHelper.cs(2,19): error CS0138: `UnityEngine.GUI’ is a type not a namespace. A using namespace directive can only be applied to namespaces

Что делать?

Вот мой код:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using UnityEngine;
using UnityEngine.GUI;
using System.Collections;
 
public class GameHelper : MonoBehaviour {
 
    public Text PlayerGoldGUI;
 
    public int PlayerGold;
 
    // Use this for initialization
    void Start () {
    
    }
    
    // Update is called once per frame
    void Update () {
    
    }
}

пожалуйста помогите .



0



2502 / 1515 / 806

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

Сообщений: 3,701

20.06.2019, 23:05

10

Эдис, почему и для чего вы написали эту строку using UnityEngine.GUI;?



1



3088 / 1617 / 921

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

Сообщений: 4,620

20.06.2019, 23:17

11

Наверное там должно быть UnityEngine.UI;



1



Эдис

0 / 0 / 0

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

Сообщений: 14

21.06.2019, 07:37

 [ТС]

12

Потому что когда я пишу Text на 7 строчке он не работает — загорается красным. Для этого я на второй строчке написал using UnityEngine.GUI;

Добавлено через 4 минуты
Не попробовал всё же выходят ошибки
Если кто знает помогите в конце урока застрял я

Я это делал по видео уроку :

Только у него старые коды — не работают сейчас поэтому спрашивал.

Добавлено через 4 минуты
А не всё я нашел ответ:
Просто поменял местами и закрыл using UnityEngine.GUI;
потом перед текстом поставил GUI .

Добавлено через 12 секунд

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using UnityEngine;
//using UnityEngine.;
using System.Collections;
 
public class GameHelper : MonoBehaviour {
 
    public GUIText PlayerGoldGUI;
 
    public int PlayerGold;
 
    // Use this for initialization
    void Start () {
    
    }
    
    // Update is called once per frame
    void Update () {
    
    }
}



0



3088 / 1617 / 921

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

Сообщений: 4,620

21.06.2019, 09:08

13

Какой же ты невнимательный, кошмар.

Добавлено через 1 минуту
И у парня в уроке Text, а не GUIText.



0



250 / 186 / 68

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

Сообщений: 1,010

21.06.2019, 09:39

14

Цитата
Сообщение от Эдис
Посмотреть сообщение

Я это делал по видео уроку

уроки то обрезанные. что вы сможете по ним научиться. догадываться что там дальше?



0



0 / 0 / 0

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

Сообщений: 2

01.07.2022, 19:13

15

помогите мне пожалуйста



0



Получение переменной из другого скрипта

Получение переменной из другого скрипта

Знаю, что таких вопросов очень много… Но у меня просто пишет ошибку.
Текст ошибки:
Assets/scripts/shooter.cs(10,64): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
Вот скрипт:

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

using UnityEngine;
using System.Collections;

public class shooter : MonoBehaviour {
        public float maxSpeed = 13f;
        private float move = 0;
        public bool isFacing = true;
        public void FixedUpdate()
        {
                GetComponent<SheenaController> ().isFacingRight;
                if (isFacingRight == true) {
        move = 1;
                } else {
        move = 1;
                }
                GetComponent<Rigidbody2D>().velocity = new Vector2 (move * maxSpeed, GetComponent<Rigidbody2D>().velocity.y);
}
}

Подскажите в чём ошибка?
Заранее всем спасибо!))

Аватара пользователя
Dragon-FAST
UNIт
 
Сообщения: 92
Зарегистрирован: 15 авг 2016, 08:29

Re: Получение переменной из другого скрипта

Сообщение greatPretender 14 фев 2017, 07:30

void Start(){
isFacing = GetComponent<SheenaController> ().isFacingRight;

}

greatPretender
Старожил
 
Сообщения: 526
Зарегистрирован: 23 сен 2015, 07:51

Re: Получение переменной из другого скрипта

Сообщение Rpabuj1 14 фев 2017, 11:23

Скрипты должны висеть на объектах. То есть, сначала берем объект, потом скрипт на нем, потом переменную.

имя_объекта.getComponent<имя_скрипта>().имя_переменной;

Rpabuj1
Старожил
 
Сообщения: 639
Зарегистрирован: 04 авг 2015, 12:07

Re: Получение переменной из другого скрипта

Сообщение Dragon-FAST 14 фев 2017, 11:59

Rpabuj1 писал(а):Скрипты должны висеть на объектах. То есть, сначала берем объект, потом скрипт на нем, потом переменную.

имя_объекта.getComponent<имя_скрипта>().имя_переменной;

Спасибо получилось как раз по твоей компоновке!))
кому может понадобиться вот мой скрипт:

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

using UnityEngine;
using System.Collections;

public class shooter : MonoBehaviour {
        public int move = 1;
        public bool lr = true;
        public GameObject sheena;
        public void Start()
        {
                lr = sheena.GetComponent<SheenaController> ().isFacingRight;
                if (lr == true) {
                        move = 1;
                } else {
                        move = 1;
                }
        }
        public void FixedUpdate()
        {
                if (move > 0) {
                        GetComponent<Rigidbody2D> ().AddForce (new Vector2 (20, 0));
                } else {
                        GetComponent<Rigidbody2D> ().AddForce (new Vector2 (20, 0));
                }
}
        public void Update(){
                Destroy (gameObject, 1);
        }
}

Аватара пользователя
Dragon-FAST
UNIт
 
Сообщения: 92
Зарегистрирован: 15 авг 2016, 08:29

Re: Получение переменной из другого скрипта

Сообщение Rpabuj1 14 фев 2017, 12:25

Dragon-FAST писал(а):

Rpabuj1 писал(а):Скрипты должны висеть на объектах. То есть, сначала берем объект, потом скрипт на нем, потом переменную.

имя_объекта.getComponent<имя_скрипта>().имя_переменной;

Спасибо получилось как раз по твоей компоновке!))
кому может понадобиться вот мой скрипт:

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

using UnityEngine;
using System.Collections;

public class shooter : MonoBehaviour {
        public int move = 1;
        public bool lr = true;
        public GameObject sheena;
        public void Start()
        {
                lr = sheena.GetComponent<SheenaController> ().isFacingRight;
                if (lr == true) {
                        move = 1;
                } else {
                        move = 1;
                }
        }
        public void FixedUpdate()
        {
                if (move > 0) {
                        GetComponent<Rigidbody2D> ().AddForce (new Vector2 (20, 0));
                } else {
                        GetComponent<Rigidbody2D> ().AddForce (new Vector2 (20, 0));
                }
}
        public void Update(){
                Destroy (gameObject, 1);
        }
}

Рад, что смог помочь :)
Удачи вам!

Rpabuj1
Старожил
 
Сообщения: 639
Зарегистрирован: 04 авг 2015, 12:07


Вернуться в Почемучка

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

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



Понравилась статья? Поделить с друзьями:
  • Unity error cs0116 a namespace cannot directly contain members such as fields or methods
  • Unity error cs0106 the modifier public is not valid for this item
  • Unity error adding package
  • Unique violation 7 error duplicate key value violates unique constraint
  • Unindent does not match any outer indentation level python как исправить