【问题标题】:error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement错误 CS0201:只有赋值、调用、递增、递减、等待和新对象表达式可以用作语句
【发布时间】:2017-02-23 20:19:06
【问题描述】:

使用 Unity,我正在尝试将带有特定脚本的 GameObjects 添加到数组中。我尝试了很多不同的方法,最终我得到了这个,对于我的生活,我找不到它为什么给我这个错误,因为我在过去一小时谷歌搜索的所有内容都说它是主要来自语法,我找不到语法错误。我想知道使用 get/set 是否有意义,但我真的不明白它们与 for 循环有何不同。谢谢!

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];

        }
    }
}

}

【问题讨论】:

  • 你呃...复习how you actually use .Add()的语法了吗?
  • 嗯,是吗?这在其他代码中对我有用,所以我不确定问题是什么。当我使用括号时,它给了我同样的错误。
  • Add 是一个函数,因此你需要一个 ()。像这样的东西:interactables.Add( iset.gameObject);
  • 完美,解决了我的问题。感谢您的帮助!

标签: c# arrays unity3d


【解决方案1】:

感谢您的意见,我已经解决了这个问题——部分问题是我没有意识到我引用的脚本是一个孩子,而不是游戏对象本身的一个组件。但如果有人好奇:

    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);
        }
    }

【讨论】:

    【解决方案2】:

    第一个问题:正如 Pogrammer 所说,Add 是列表的函数,而不是索引器。

    Add(i) 是正确的

    当然,错误是由于您的第一个问题造成的。

    第二个问题:游戏对象的Interactables os列表,您尝试将整数(i是整数)添加到游戏对象列表中。

    查看您的代码并了解您要添加到 Interactables 的内容。

    【讨论】:

      猜你喜欢
      • 2015-07-05
      • 2020-11-24
      • 2020-04-08
      • 1970-01-01
      • 2023-03-05
      • 2013-09-13
      • 1970-01-01
      • 2014-01-04
      • 2016-06-27
      相关资源
      最近更新 更多