【问题标题】:How to enable disabled gameobject in unity如何统一启用禁用的游戏对象
【发布时间】:2017-03-17 06:41:12
【问题描述】:

我想禁用一个游戏对象,为此我编写了如下代码:

GameObject go;
go = GameObject.FindWithTag("MainCamera");
Destroy(go);

然后我正在努力启用该禁用的游戏对象。

有人可以在这方面帮助我吗?

【问题讨论】:

    标签: unity3d destroy gameobject


    【解决方案1】:

    当调用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();
     }
    

    【讨论】:

    • 如果被标记为MainCamera,则无需搜索,使用Camera.main
    • 发帖人用了GameObject.FindWithTag,所以我也用了。这是一般方法。也许,他会改变主意,他会想要找到一个带有不同标签的游戏​​对象。
    【解决方案2】:

    重复的问题但是.....

    https://docs.unity3d.com/ScriptReference/GameObject.SetActive.html

    提示:

    go.SetActive(!go.activeInHierarchy); // 切换游戏对象。

    go = GameObject.FindWithTag("TADA") // 更好

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-08
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多