Rea*_*Gas 1 c# scope unity-game-engine
所以我试图从FindGameObjectsWithTag初始化的GameObject数组中访问一个元素,但是我收到以下错误
"IndexOutOfRangeException:数组索引超出范围.",
当我打印数组的长度时,我得到3,应该是.我如何解决它?
public class selectObject : MonoBehaviour {
// Use this for initialization
public GameObject[] objects;
void Start () {
GameObject[] objects = GameObject.FindGameObjectsWithTag("isari");
Debug.Log (objects.Length);
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Mouse is down");
RaycastHit hitInfo = new RaycastHit();
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
if (hit)
{
Vector3 position = hitInfo.transform.gameObject.transform.position;
Quaternion rotation = hitInfo.transform.gameObject.transform.rotation;
Debug.Log("Hit " + hitInfo.transform.gameObject.name);
Object.Instantiate (objects[0], position,rotation);
Object.Destroy (hitInfo.transform.gameObject);
if (hitInfo.transform.gameObject.tag == "Construction")
{
Debug.Log ("It's working!");
} else {
Debug.Log ("nopz");
}
} else {
Debug.Log("No hit");
}
Debug.Log("Mouse is down");
}
}
}
Run Code Online (Sandbox Code Playgroud)
您objects[]在Start隐藏字段的函数中声明了一个局部变量objects.只需objects从start函数中删除数组的声明
你可以试试这个.
public GameObject[] objects;
void Start () {
objects = GameObject.FindGameObjectsWithTag("isari");
Debug.Log (objects.Length);
}
Run Code Online (Sandbox Code Playgroud)