继承不适用于多维数组

问题描述 投票:0回答:1

我尝试使用继承从 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]); //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
    }
}

我还检查了另一个变量,看来问题只出在多维数组上。一维数组可以正常工作,与 int、float、string 等相同。我该如何解决这个问题?

P.S:抱歉我的英语不好

c# inheritance multidimensional-array
1个回答
0
投票

您需要制定您的

Awake
方法
protected
,例如

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

    protected virtual 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
{
    protected override void Start()
    {
        Debug.Log(boardFields[4, 0]); //and here i get null in the console
    }
}

Unity 无法

inherited
类上找到 Awake 方法,因为默认情况下
private
方法是隐藏的。

Unity 只能找到在同一个类上声明的

private
成员(即
private
方法不是继承的)。

如果您在

base
类中创建
Awake()
方法 protected,那么 Unity 将能够找到它。

然后需要创建继承类的方法

protected override

您应该发现您只获得一个调试日志(来自

Start()
),而不是预期的两个(另一个来自 基类
Awake()
)。当你解决这个问题时,你应该得到两个日志,并且数组不会是
null

© www.soinside.com 2019 - 2024. All rights reserved.