繁体   English   中英

Unity3D:计数带有特定GameObject标签的子代时出错

[英]Unity3D: Error in counting children with tag of specific GameObject

Unity3D 2018.2.5

我有一个名为“ MainObject”的GameObject,它下面还有其他几个GameObjects作为名为SideObjects的子级,并带有标签“ High”和“ Low”。 由于MainObject中有几个不同的GameObject,因此我试图对它们进行计数。

我试图计算标签“ High”中“ MainObject”中有多少个GameObject。

到目前为止,这是我尝试从父GameObject的子代获取标签的代码,但出现错误。

错误:

ArgumentException:GetComponent要求所请求的组件“列表1' derives from MonoBehaviour or Component or is an interface. UnityEngine.GameObject.GetComponentInChildren[List 1' derives from MonoBehaviour or Component or is an interface. UnityEngine.GameObject.GetComponentInChildren[List 1](布尔值includeInactive)(在C:/buildslave/unity/build/Runtime/Export/GameObject.bindings.cs:70)

代码我有:

public void getListOfObjectsInMain()
{
    // Reset count before counting
    objCountInMain = 0;

    //  Count amount of children in camera transform
    GameObject currentMain = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<HandleCamera>().targetToLookAt.gameObject;

     // Debug.Log(currentMain);

    List<GameObject> allObjectsInMain = currentMain.GetComponentInChildren<List<GameObject>>(false);

    foreach (GameObject obj in allObjectsInMain)
    {
        if (obj.gameObject.tag == "High")
        {
            objCountInMain++;
        }
    }

    //  Text
    objInMainText.text = objCountInMain.ToString();
}

几个问题:

1 GameObject[] allObjectsInMain = currentMain.GetComponentInChildren

GetComponentInChildren函数用于从GetComponentInChildren中获取一个组件。 试图使其返回一个数组或多个对象将引发异常。

2 currentMain.GetComponentInChildren<List<GameObject>>(false);

你可以不通过GameObjectGetComponentInChildren功能,因为游戏对象不是同一的一个组成部分。 组件连接到GetComponentXXX ,而GetComponentXXX函数仅返回组件,而不返回GetComponentXXX 因此,其中包含组件关键字。

同样,您也无法将List传递给它。 传递给该函数的唯一一件事是从MonoBehaviourinterface或任何内置组件(如Rigidbody组件)继承的组件或脚本。


使用GetComponentsInChildren与功能s在里面。 那将返回多个对象。 同样,将Transform传递给它,因为Transform是一个组件,并且场景中的每个GameObject都有一个Transform组件,因此可以用来查找所有子对象。

int CountChildObjectsByTag(GameObject parent, string tag)
{
    int childCount = 0;
    Transform[] ts = parent.GetComponentsInChildren<Transform>();
    foreach (Transform child in ts)
    {
        if (child != parent.transform && child.CompareTag(tag))
            childCount++;
    }
    return childCount;
}

更好的是,只需遍历transform 现在,您不必每次调用此函数时都使用GetComponentsInChildren或返回一个数组。

int CountChildObjectsByTag(GameObject parent, string tag)
{
    int childCount = 0;
    foreach (Transform child in parent.transform)
    {
        if (child.CompareTag(tag))
            childCount++;
    }
    return childCount;
}

用法:

GameObject currentMain = GameObject.FindGameObjectWithTag("MainCamera");
int childCount = CountChildObjectsByTag(currentMain, "High");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM