簡體   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