我有一个脚本,该脚本应该在我的GameObject上切换活动状态,但是当禁用它时,它将不再找到该对象。
脚本:
GameObject cheet = GameObject.Find("base");
if (isOpen == true)
{
cheet.SetActive(true);
}
else
{
cheet.SetActive(false);
}
GameObject.Find仅返回活动的GameObject,因此我建议将对cheet的引用存储在Start()
或Awake()
中。只要Cheet存在,这将确保您具有参考并且您只需要做一次。
using UnityEngine;
public class YourClass : MonoBehaviour
{
private GameObject cheet;
private bool isOpen; // Temp isOpen variable
void Start()
{
// Store a reference to the GameObject
cheet = GameObject.Find("base");
}
void Example1()
{
// set active based on varable isOpen
cheet?.SetActive(isOpen);
}
void Example2()
{
// Could not find cheet (null)
if(cheet == null)
return;
// set active based on varable isOpen
cheet.SetActive(isOpen);
}
}