解决“使子项超出范围”异常 [英] Addressing 'Transform child out of bounds' exception
问题描述
当父级<$ c $时,我将子级 GameObject
的 SetActive
设置为true。 c> GameObject 被触发。
I'm going to set the child GameObject
's SetActive
to true when the parent GameObject
is triggered.
像这张照片一样, BallIndigo1
是父级 GameoOject
和 x
是子对象 GameObject
,位于 SetActive(false)
中。
Like this picture, BallIndigo1
is the parent GameoOject
and x
is the child GameObject
which is in SetActive(false)
.
,我这样编写代码:
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");
}
}
}
但结果显示:
我不知道为什么会这样,如何解决它。
I don't know why this happened and how to fix it.
推荐答案
之所以会这样,是因为GameObject传递给了 OnTriggerEnter2D
函数 col.transform
没有孩子。您可以通过检查 col.transform.childCount>来解决此问题。 0
,然后调用 col.transform.GetChild(0)
。
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");
}
}
}
如果您100%确定此对象有子对象,则将检测到另一个没有子对象的GameObject。您必须在调用 col.transform.GetChild(0)
之前按 tag 或 layer 过滤此GameObject。创建一个名为 Ball的标签,将要检测的对象设置为此标签。确保此球对象有一个孩子。下面的代码应检查该标记,并应避免该错误。
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");
}
}
}
}
这篇关于解决“使子项超出范围”异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!