英文:
How to get array from base class on child class
问题
你好。我尝试在脚本B中通过继承从脚本A获取多维数组,但在调用脚本B上的数组后,数组为空。
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
}
}
我还检查了其他变量,似乎问题只出现在数组中。如何在脚本B中使用这个数组?对不起,也许这是一个愚蠢的问题,但我刚刚开始学习面向对象编程。
英文:
Helo. 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 arrays. How can i use this array in scriptB? Sorry for maybe stupid question but i just started with object programming
答案1
得分: 1
问题出在访问修饰符上。
void Awake()
{
}
默认为私有方法。所以当Unity通过反射在ScriptB
中搜索该方法时,它无法访问它们。
所以尝试使用不同的访问修饰符,比如protected
来继承行为。
另一种方法是在层次结构中的所有类中定义Awake()
,或者您可以像下面这样重用代码:
public class ScriptA : MonoBehaviour
{
protected GameObject[,] boardFields = new GameObject[8, 8];
void Awake()
{
Setup();
Debug.Log(boardFields[4, 0]); //在这里我在控制台看到该变量不是空的
//其余的代码
}
protected void Setup()
{
boardFields[4, 0] = GameObject.Find("Canvas/Board/Fields/A4");
}
}
public class ScriptB : ScriptA
{
void Awake()
{
Setup();
}
void Start()
{
Debug.Log(boardFields[4, 0]); //在这里我在控制台得到null
}
}
英文:
The issue is in access modifiers.
void Awake()
{
}
defaults as a private method. So when Unity search the method in ScriptB
via reflection it just does have access to them.
So try to use different access modifier like protected
to inherit behaviour.
The other ways is to define Awake()
in all classes in your hierarchy, or you can reuse code like below
public class ScriptA : MonoBehaviour
{
protected GameObject[,] boardFields = new GameObject[8, 8];
void Awake()
{
Setup();
Debug.Log(boardFields[4, 0]); //here i see in the console that the variable is not empty
//rest of the code
}
protected void Setup()
{
boardFields[4, 0] = GameObject.Find("Canvas/Board/Fields/A4");
}
}
public class ScriptB : ScriptA
{
void Awake()
{
Setup();
}
void Start()
{
Debug.Log(boardFields[4, 0]); //and here i get null in the console
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论