【问题标题】:Very simple code - Unity 3d - IndexOutOfRangeException: Index was outside the bounds of the array非常简单的代码 - Unity 3d - IndexOutOfRangeException:索引超出了数组的范围
【发布时间】:2020-02-18 18:52:28
【问题描述】:
public class Button : MonoBehaviour {
    public Material[] mButton;
    Renderer rend;

    // Start is called before the first frame update
    void Start()
    {
        Debug.Log(mButton[0]);
        rend = GetComponent<Renderer>();
        rend.sharedMaterial = mButton[0];
    }

我在 rend.sharedMaterial=mButton[0] 行收到“索引超出范围”错误。它是一个包含两个元素的数组。我在阵列的两个位置都有不同的材料。 Debug.Log 准确地显示了 [0] 位置中的材料。

有什么想法吗?提前致谢。

【问题讨论】:

  • 如果您记录 sharedMaterial 会发生什么? Debug.Log(rend.sharedMaterial)
  • 您能否再次检查错误发生在 rend.sharedMaterial 行,而不是 Debug.Log 行? (例如,有时会意外地将相同的脚本分配给两个不同的游戏对象——一个现在会有一个空的材质列表,因此会在 Debug.Log 行抛出错误。)
  • @SérgioCastelani 抱歉耽搁了,我正在尝试另一种方法。如果我将 'rend.sharedMaterial' 放在 debug.log 中,我会收到以下错误:“NullReferenceException:对象引用未设置为对象的实例”
  • @PhilippLenssen 解决了!谢谢!你能把它放在一个答案中,以便我可以选择它吗?

标签: arrays unity3d indexoutofboundsexception


【解决方案1】:

@PhilippLenssen 发表的评论解决了这个问题。

他的评论: “您能否再次检查错误是否发生在 rend.sharedMaterial 行,而不是 Debug.Log 行?(例如,有时会发生一个意外将相同的脚本分配给两个不同的游戏对象 - 现在一个是空的材料列表,因此会在 Debug.Log 行抛出错误。) "

一旦我注释掉 Debug.Log(mButton[0]); 行,错误就清除了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-17
    • 2015-01-12
    相关资源
    最近更新 更多