[英]Unity3d C# Trying to access array in script but in void
我已经尝试解决这个问题好几个小时了,但我就是想不通。
我需要访问数组“空格中的字母“nextItem”和“prevItem”,但我收到一条错误消息,指出“ArgumentException:GetComponent 要求请求的组件‘GameObject[]’来自 MonoBehaviour 或 Component 或者是一个接口。”
using UnityEngine;
using System.Collections;
public class buttons_abc : MonoBehaviour {
public int id;
public GameObject[] letters;
// Use this for initialization
void Start () {
id = 0;
GameObject[] letters = GameObject.FindGameObjectsWithTag ("letter");
letters[id].SetActive (true);
for (int i = 1; i < 32; i++) {
letters[i].SetActive (false);
}
}
public void nextItem(){
letters = GetComponent<GameObject[]>();
Debug.Log (id);
if(id < 32){
letters[id].SetActive (false);
letters[id + 1].SetActive (true);
id++;
} else {
Debug.Log("viimane t2ht");
}
}
public void prevItem(){
letters = GetComponent<GameObject[]>();
Debug.Log (id);
if(id > 0){
letters[id].SetActive(false);
letters[id-1].SetActive(true);
id--;
} else{
Debug.Log("esimene t2ht");
}
} }
你的代码中有太多错误的东西。
声明名为letters
游戏对象,然后再次在Start()
函数中重新声明它。
letters = GetComponent<GameObject[]>();
覆盖当前的 GameObject 引用?
GetComponent<GameObject[]>();
你不能这样做。(你的主要错误)
for (int i = 1; i < 32; i++) { letters[i].SetActive (false); }
您无法检查您的数组是否越界。 i< 32
应该是letters.Length
您的脚本中有一些错误。
1.有没有GetComponent可以返回一个游戏对象EVER。 时期。 GetComponent 函数用于获取附加到 GameObject 的 SINGLE 组件。
2. 话虽如此,GetComponent 也不能返回数组。 您要查找的类型GetComponent<GameObject[]>
无效。 有效的 GetComponents 调用如下所示
GetComponent<AudioSource>();
letters
。 然后,您将在 Start 中创建另一个数组,这次是在本地,将其称为相同的内容( letters
)。把这一切放在一起
using UnityEngine;
using System.Collections;
public class buttons_abc : MonoBehaviour {
public int id;
public GameObject[] letters;
// Use this for initialization
void Start () {
id = 0;
//Already declared letters globally. Creating another one here locally will mean that your global array will not be populated
//GameObject[] letters = GameObject.FindGameObjectsWithTag ("letter");
letters = GameObject.FindGameObjectsWithTag ("letter");
letters[id].SetActive (true);
for (int i = 1; i < 32; i++) {
letters[i].SetActive (false);
}
}
public void nextItem(){
//GetComponent only works on Components. GameObjects are NEVER components
//GetComponent cannot return an array
//letters = GetComponent<GameObject[]>();
Debug.Log (id);
if(id < 32){
letters[id].SetActive (false);
letters[id + 1].SetActive (true);
id++;
} else {
Debug.Log("viimane t2ht");
}
}
public void prevItem(){
//See comment from nextItem()
//letters = GetComponent<GameObject[]>();
Debug.Log (id);
if(id > 0){
letters[id].SetActive(false);
letters[id-1].SetActive(true);
id--;
} else{
Debug.Log("esimene t2ht");
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.