我正在使用协同程序功能,但我单击下一步按钮时应创建新对象,以销毁旧对象
public class SceneChanger: MonoBehaviour
{
private List<string> sceneHistory = new List<string>(); //running history of scenes
public GameObject[] charset; //The last string in the list is always the current scene running
public GameObject changer;
public int chartotalnum = 3;
public float Timer;
public int rand;
public Button Next;
public GameObject go;
void Start()
{
GameObject go = Instantiate(charset[rand], new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
Destroy(go, 5f);
rand++;
//StartCoroutine(Spawn());
Button btn = Next.GetComponent<Button>();
btn.onClick.AddListener(ClickedNext);
//DontDestroyOnLoad(this.gameObject); //Allow this object to persist between scene changes
}
void Update()
{
}
IEnumerator Spawn()
{
yield return new WaitForSeconds(5f);
GameObject go = Instantiate(charset[rand], new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
Debug.Log("test");
rand++;
Destroy(go, 5f);
}
public void ClickedNext()
{
StopCoroutine(Spawn());
Destroy(go);
go = Instantiate(charset[rand], new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
rand++;
Destroy(go, 5f);
Debug.Log("clicked");
StartCoroutine(Spawn());
}
}
答案 0 :(得分:1)
问题在于,在Start
和Spawn
中您都使用
GameObject go = Instantiate(charset[rand], new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
从而创建一个名为go
的局部变量,该变量将隐藏您现有的类字段go
。
它必须是
go = Instantiate(charset[rand], new Vector3(0, 0, 0), Quaternion.identity);
在Start
和Spawn
中使用现有字段代替新的局部变量。
答案 1 :(得分:0)
我从以下位置删除了gameObject go =实例化(charset [rand],将新的Vector3(0,0,0),Quaternion.identity)作为GameObject;