c# - 在遍历数组后尝试从列表中获取随机元素时出现 ArgumentOutOfRangeException 错误 Unity3D C#

标签 c# arrays list unity3d

问题: 在遍历数组后尝试从列表中获取随机元素时出现 ArgumentOutOfRangeException 错误。

目标: 我试图通过查找标签来激活父游戏对象中的随机子游戏对象。 parent 内部有多个子游戏对象。如果该游戏对象标有我正在寻找的标签,我想将其挑选出来并根据其标签将其添加到新列表中。然后在遍历该数组后,我想为每个新列表获取一个随机元素并将其设置为事件

[SerializeField] private List<Transform> heads = new List<Transform>();
[SerializeField] private List<Transform> bodys = new List<Transform>();
[SerializeField] private List<Transform> arms = new List<Transform>();
[SerializeField] private Transform[] bodyParts;

private GameObject head;
private GameObject backpack;
private GameObject arm;

void Start()
{
    bodyParts = this.gameObject.GetComponentsInChildren<Transform>();
    for (int i = 0; i < bodyParts.Length; i++)
    {
        switch (bodyParts[i].tag)
        {
            case "Head":
                heads.Add(bodyParts[i]);
                break;

            case "Arm":
                arms.Add(bodyParts[i]);
                break;

            case "Backpack":
                backpacks.Add(bodyParts[i]);
                break;

            default:
                Debug.Log("Not relevant");
                break;
        }
    }
    SetActiveBodyPart(heads, head);

    SetActiveBodyPart(arms, arm);

    SetActiveBodyPart(backpacks, backpack);
}

void SetActiveBodyPart(List<Transform> whichBodyParts, GameObject whichBodyPart)
{
    if (whichBodyParts != null)
    {
        whichBodyPart = whichBodyParts[Random.Range(0, whichBodyParts.Count)].gameObject;
        if (!whichBodyPart.activeSelf)
        {
            whichBodyPart.SetActive(true);
        }
    }
    else Debug.Log("Nothing here...");
}

我在这一行遇到错误:

whichBodyPart = whichBodyParts[Random.Range(0, whichBodyParts.Count)].gameObject;

当我手动停用父级中的所有子游戏对象并开始游戏时,Unity 编辑器中的那些列表返回 0,但我希望输出为正整数

最佳答案

如果您想在 GetComponentsInChildren 的结果中包含停用的组件,您需要包含 includeInactive 参数并将其设置为 true。此外,将 this.gameObject 放在 GetComponentsInChildren 之前是多余的:

bodyParts = GetComponentsInChildren<Transform>(true);

要处理无论如何都会得到空列表的情况,您还应该包括一个避免索引到空列表的检查:

if (whichBodyParts != null && whichBodyParts.Count > 0)
{
    whichBodyPart = whichBodyParts[Random.Range(0, whichBodyParts.Count)].gameObject;
    if (!whichBodyPart.activeSelf)
    {
        whichBodyPart.SetActive(true);
    }
}
else Debug.Log("Nothing here...");

关于c# - 在遍历数组后尝试从列表中获取随机元素时出现 ArgumentOutOfRangeException 错误 Unity3D C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56995175/

相关文章:

c# - 自定义验证属性的依赖注入(inject)

c# - 绑定(bind)到依赖属性魔法

php - 使用数组的 MySQL 查询

c - 对二叉树进行排序 - 函数达到 seg。过错

c# - 如何在C#中从HtmlTable中提取数据并排列成行?

c# - 防止自动命名空间前缀

c++ - 循环数组(队列)迭代器

php - 如何在以下场景中操作数组?

html - 列表样式类型 :none & list-style:none not working

python - 如何将此模板列表与单词列表进行比较?