首页 > 解决方案 > 仅向一级子级添加脚本

问题描述

我试图只获取 GameObject 的第一级子级,并为每个第一级子级添加一个脚本。

我收到一个错误:addNavTagChildren.cs(14,21): error CS0161: 'getFirstChildren(Transform)': 并非所有代码路径都返回一个值

这是我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class addNavTagChildren : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        List<GameObject> childrenList = new List<GameObject>();

        //TEST

        Transform[] getFirstChildren(Transform parent)
        {
            Transform[] children = parent.GetComponentsInChildren<Transform>();
            Transform[] firstChildren = new Transform[parent.childCount];
            int index = 0;
            foreach (Transform child in children)
            {
                if (child.parent == parent)
                {
                    firstChildren[index] = child;
                    index++;
                    childrenList.Add(child.gameObject);
                }
            }
        }

        for (int i = 0; i < childrenList.Count; i++)
        {
            NavMeshSourceTag nmst = childrenList[i].AddComponent<NavMeshSourceTag>();
        }
    }
}

标签: c#unity3d

解决方案


该行Transform[] getFirstChildren(Transform parent)是一个方法声明。您是在告诉编译器该方法getFirstChildren将返回 type 的对象Transform[]。但是,在您的方法实现中,您不会返回任何内容。这就是错误所抱怨的。如果我正确理解您的代码,您可能打算在循环return firstChildren;之后添加?foreach


推荐阅读