如何激活child的parentobject?

How to activate a child of a parent object?

我有一个 parent object 直到游戏后期才会被激活。所以我想只在进入触发器时激活。

using UnityEngine;
using System.Collections;

public class SetActiveOnTriggerEnter : MonoBehaviour {

    //public string FindGameOBJ; <-To be implemented for future re-usability. Ignore it for now.
   // public string ComponentToActivate; <-To be implemented for future re-usability. Ignore it for now.

    void OnTriggerEnter (Collider coll) // Collision detection.
    {
        if (coll.tag == "Ball") //Checks the tag to see if it is the PARENT OBJECT.
        {
                if (GameObject.Find("BallHealZone") == null) //Looks for the CHILD OBJECT, and if it is null than move forward.
                {
                    Debug.Log("Activating BallHealZone! :)"); //Tells me if it found said object, and confirms it is indeed null (yes it works).
                    gameObject.SetActive(true); //Activates the CHILD OF PARENT OBJECT.
                }
        }
    }

}

基本上如您所见,它检查标签是否正确找到游戏对象(child 是应该激活的),记录它,并应该将其设置为活动。日志显示满足条件,但不会触发 gameObject.SetActive(true);命令。

如何激活 child 或 parent object?

从外观上看 GameObject.Find("BallHealZone") returns 对 gameObject 的引用,如果 gameObject 是 null,这意味着尚未创建该对象的引用。通常这意味着您在执行方法之前实例化对象,除非它是静态方法。

尝试插入 gameObject = new WHATEVEROBJECTTHISIS();

如果不是这种情况,您能否用更多细节扩展代码片段。令我困扰的是,如果对象为空,您应该得到一个异常。我不知道为什么会发生这种情况。

首先,您无法使用 GameObject.Find() 方法找到已停用的游戏对象。因为 GameObject.Find() 找到 return "gameObject" 但是你的场景中没有这个名字的游戏对象。你应该找到这个游戏对象的变换。所以如果你想激活子对象,试试这个。

(我想这个脚本附加到父对象)

using UnityEngine;
using System.Collections;

public class SetActiveOnTriggerEnter : MonoBehaviour {

    //public string FindGameOBJ; <-To be implemented for future re-usability. Ignore it for now.
    // public string ComponentToActivate; <-To be implemented for future re-usability. Ignore it for now.

    void OnTriggerEnter (Collider coll) // Collision detection.
    {
        if (coll.tag == "Ball") //Checks the tag to see if it is the PARENT OBJECT.
        {
                if (!transform.FindChild("BallHealZone").gameObject.activeInHierarchy) //This is better form for looking , but there is a one better way, GetChild. You can see it on below. 
                {
                    Debug.Log("Activating BallHealZone! :)"); //Tells me if it found said object, and confirms it is indeed null (yes it works).
                    transform.FindChild("BallHealZone").gameObject.SetActive(true); //Activates the CHILD OF PARENT OBJECT.
                    //or if you know index of child in parent you can use GetChild method for a faster one
                    transform.GetChild(indexOfChild).gameObject.SetActive(true); // this also activates child, but this is faster than FindChild method
                }
        }
    }
}

希望对您有所帮助。