我想禁用GameObject,为了达到这个目的,我编写了这样的代码:
GameObject go;
go = GameObject.FindWithTag("MainCamera");
Destroy(go);
然后我正在努力启用那个禁用的GameObject。
有人可以帮我这方面吗?
答案 0 :(得分:2)
调用Destroy
时,你......破坏游戏对象,你不会禁用它。相反,请使用SetActive。
此外,请避免使用FindXXX
等功能,特别是多次使用。在检查器中添加引用
// Drag & Drop the gameobject in the inspector
public GameObject targetGameObject ;
public void DisableGameObject()
{
targetGameObject.SetActive( false ) ;
}
public void EnableGameObject()
{
targetGameObject.SetActive( true ) ;
}
public void ToggleGameObject()
{
if( targetGameObject.activeSelf )
DisableGameObject() ;
else
EnableGameObject();
}
否则,在启动功能或尝试禁用游戏对象时找到对象一次。请记住,FindXXX
函数无法找到禁用的游戏对象(大部分时间)
// Drag & Drop the gameobject in the inspector
private GameObject targetGameObject ;
public void DisableGameObject()
{
if( targetGameObject == null )
targetGameObject = GameObject.FindWithTag("MainCamera");
if( targetGameObject != null )
targetGameObject.SetActive( false ) ;
}
public void EnableGameObject()
{
if( targetGameObject != null )
targetGameObject.SetActive( true ) ;
}
public void ToggleGameObject()
{
if( targetGameObject == null )
targetGameObject = GameObject.FindWithTag("MainCamera");
if( targetGameObject == null )
return ;
if( targetGameObject.activeSelf )
DisableGameObject() ;
else
EnableGameObject();
}
答案 1 :(得分:0)
重复的问题但是......
https://docs.unity3d.com/ScriptReference/GameObject.SetActive.html
提示:
go.SetActive(!go.activeInHierarchy); //切换游戏对象。
go = GameObject.FindWithTag(“TADA”)//更好