我在编程方面非常陌生,我需要帮助来解决出现的问题。我试图访问另一个脚本中的数组,通常没有问题。但是我的情况是这样的:
例如:
脚本A包含一些具有不同非数字名称的数组。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ScriptA : MonoBehaviour {
public int[] keys = new int[4];
public int[] screws= new int[4];
public int[] nails= new int[4];
public int[] iron= new int[4];
....
}
现在,在脚本B中,我需要使用一个变量来访问这些数组。我怎样才能做到这一点?
例如:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ScriptB: MonoBehaviour {
ScriptA scriptA;
public string arrayName; // Here user could type in the name of an array
void Start()
{
scriptA = GameObject.Find("Object").GetComponent<ScriptA>();
// This try to access the array of course not works. But how?
scriptA.arrayname;
}
感谢您的想法和解决方案。我认为这不是一个难题,但是我不知道要解决它。
您要么需要反射(难看),要么可以定义Dictionary<string, int[]>
in ScriptA
,如下所示:
public class ScriptA : MonoBehaviour
{
public int[] keys = new int[4];
public int[] screws = new int[4];
public int[] nails = new int[4];
public int[] iron = new int[4];
public Dictionary<string, int[]> arrays;
void Start()
{
arrays = new Dictionary<string, int[]>
{
{ "keys", keys },
{ "screws", screws },
{ "nails", nails },
{ "iron", iron }
};
}
}
然后,您可以ScriptB
像这样使用它:scriptA.arrays[arrayName]
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句