Addressing 'Transform child out of bounds'

2020-04-21 04:47发布

I'm going to set the child GameObject's SetActive to true when the parent GameObject is triggered.

enter image description here

Like this picture, BallIndigo1 is the parent GameoOject and x is the child GameObject which is in SetActive(false).

and I wrote code like this:

void OnTriggerEnter2D(Collider2D col)
{
    if (col.gameObject.activeSelf == true)
    {
        if (col.transform.GetChild(0) != null)
        {
            col.transform.GetChild(0).gameObject.SetActive(true);
        }
        else
        {
            Debug.Log("No child");
        }
    }
}

But the result says:

enter image description here

I don't know why this happened and how to fix it.

1条回答
Root(大扎)
2楼-- · 2020-04-21 05:08

You are getting this because the GameObject passed to the OnTriggerEnter2D function col.transform doesn't have a child. You can fix that by checking if col.transform.childCount > 0 before calling col.transform.GetChild(0).

void OnTriggerEnter2D(Collider2D col)
{
    if (col.gameObject.activeSelf == true)
    {
        if (col.transform.childCount > 0 && col.transform.GetChild(0) != null)
        {
            col.transform.GetChild(0).gameObject.SetActive(true);
        }
        else
        {
            Debug.Log("No child");
        }
    }
}

If you are 100% sure that this Object has a child then there is another GameObject that is being detected that doesn't have a child. You must filter this GameObject out by tag or layer before calling col.transform.GetChild(0). Create a tag named "Ball" set the Objects you want to detect to this tag. Make sure that the this "Ball" object has a child. The code below should check for that tag and should get ride of that error.

void OnTriggerEnter2D(Collider2D col)
{
    if (col.CompareTag("Ball"))
    {
        if (col.gameObject.activeSelf == true)
        {
            if (col.transform.GetChild(0) != null)
            {
                col.transform.GetChild(0).gameObject.SetActive(true);
            }
            else
            {
                Debug.Log("No child");
            }
        }
    }
}
查看更多
登录 后发表回答