继承不适用于多维数组。

huangapple go评论60阅读模式
英文:

Inheritance doesn't work with multidimensional array

问题

我试图在ScriptB中使用继承从ScriptA获取多维数组,但在调用ScriptB中的此数组后,数组为空。

public class ScriptA : MonoBehaviour
{
    protected GameObject[,] boardFields = new GameObject[8, 8];

    void Awake()
    {
        boardFields[4, 0] = GameObject.Find("Canvas/Board/Fields/A4");
        Debug.Log(boardFields[4, 0]); //在控制台中看到变量不为空
        //其余的代码
    }
}

public class ScriptB : ScriptA
{
    void Start()
    {
        Debug.Log(boardFields[4, 0]); //在控制台中得到null
    }
}

我还检查了其他变量,似乎问题只出现在多维数组中。单维数组正常工作,就像int、float、string等一样。我该如何解决这个问题?

P.S:对不起,我的英文不太好。

英文:

i try to get multidimensional array from scriptA in scriptB using inheritance and it seems like after calling this array on scriptB, array is empty.

public class ScriptA : MonoBehaviour
{
    protected GameObject[,] boardFields = new GameObject[8, 8];

    void Awake()
    {
        boardFields[4, 0] = GameObject.Find("Canvas/Board/Fields/A4");
        Debug.Log(boardFields[4, 0]); //here i see in the console that the variable is not empty
        //rest of the code
    }
}

public class ScriptB : ScriptA
{
    void Start()
    {
        Debug.Log(boardFields[4, 0]); //and here i get null in the console
    }
}

I also checked another variables and it seems that the problem is only with multidimensional array. Singledimensional arrays work normally, same as int, float, string etc.. How can i solve this trouble?

P.S: Sorry for my bad english

答案1

得分: 0

你需要将你的 Awake 方法改为 protected。例如:

protected void Awake(){
// 等等。
}

Unity 无法在继承的类中找到 Awake 方法,因为默认情况下 private 方法是隐藏的。你应该注意到你只会得到一个调试日志(来自于 Start()),而不是预期的两个日志(另一个来自于基类的 Awake())。当你修复这个问题后,你应该会得到两个日志,并且数组不会为空。

英文:

You need to make your Awake method protected. E.g.

protected void Awake(){
// etc.
}

Unity cannot find the Awake method on the inherited class, since private methods are hidden by default. You should find that you only get one debug log (from Start()), and not the expected two (the other being from the base class Awake()). When you fix this, you should get two logs, and the array won't be null.

huangapple
  • 本文由 发表于 2023年7月13日 21:14:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76679775.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定