如何激活父对象的子级?

时间:2016-01-07 00:27:13

标签: c# unity3d parent-child

我有一个父对象,直到游戏后期才会被激活。所以我想只在它进入触发器时激活。

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.
                }
        }
    }

}

基本上你可以看到它检查标签是否正确找到GameObject(孩子是一个应该被激活的孩子),记录它,并且应该将它设置为活动状态。日志说条件已满足,但它没有触发gameObject.SetActive(true);命令。

如何激活父对象的子级?

2 个答案:

答案 0 :(得分:0)

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

尝试插入gameObject = new WHATEVEROBJECTTHISIS();

如果不是这种情况,您可以使用更多详细信息扩展代码段。困扰我的是,如果对象为null,则应该获得异常。我不知道为什么会发生这种情况。

答案 1 :(得分:0)

首先,您无法使用GameObject.Find()方法找到已停用的游戏对象。因为GameObject.Find()找到并返回“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
                }
        }
    }
}

我希望这会有所帮助。