gpt4 book ai didi

c# - 使用 foreach 循环查找作为其他对象的子对象的游戏对象 (Unity3d)

转载 作者:太空宇宙 更新时间:2023-11-03 19:42:09 28 4
gpt4 key购买 nike

我正在制作视频游戏,虽然我有通用 C# 的现有代码,但我现在必须将其移至 Unity。我对通用 C# 有一些基础知识,但我才刚刚开始学习 Unity 编码方式。

首先,我想编写一段代码,将所有游戏区域定位到正确位置,然后将它们变为不可见。是的,不要惊讶,他们需要都在同一个地方。

区域可以有三种大小选项,我称之为小、中和大。大小区域都得手工写。

 List <GameObject> SmallAreas = new List<GameObject>();

void DefineSmallAreas()
{
SmallAreas.Add(areaConfirmLoad);
SmallAreas.Add(areaConfirmQuit);
SmallAreas.Add(areaConfirmSave);
SmallAreas.Add(areaGameSaved);
SmallAreas.Add(areaSave);
SmallAreas.Add(areaLoad);
}

与大面积相同。

现在,所有其他领域,都是中等的,而且数量很大。

所以,我想遍历“areaContainer”的所有子游戏对象,检查它们的名称是否以“area”开头,如果是,我想将它们添加到 MediumAreas 列表中。

我就是这样尝试的:

void DefineMediumAreas()
{
GameObject areaContainer = GameObject.Find("areaContainer");

foreach (GameObject thisObject in areaContainer)
{
char[] a = thisObject.Name.ToCharArray();
if (a.Length >= 4)
{
char[] b = { a[0], a[1], a[2], a[3] };
string thisObjectType = new string(b);
(if (thisObjectType == "area")&&(!(SmallAreas.Contains(thisObject))
&&(!(LargeAreas.Contains(thisObject)))
{
MediumAreas.Add(thisObject);
}
}
}

然而,这显示了一个错误,“areaContainer”不能那样使用,我现在无法访问 Unity,所以无法复制确切的消息。我认为这类似于“Gameobject 没有 IEnumerator”。

我确实尝试用谷歌搜索更好的方法,并找到了一种叫做“转换”的东西。

 foreach(Transform child in transform)
{
Something(child.gameObject);
}

我不明白的是如何在我的具体情况下使用这种“转换”。

如果这个问题很愚蠢,请不要生我的气,我是 Unity 的新手,必须从头开始学习。

还有第二个小问题。这项使物体隐形的工作是否有效:

    foreach(GameObject thisObject in MediumAreas)
{
thisObject.position = MediumVector;
thisObject.GetComponent<Renderer>().enabled = false;
}

MediumVector 是对象必须移动到的位置,它似乎在工作。

最佳答案

可以这样做:foreach(Transform child in transform)

因为 Transform 类实现了 IEnumerable 并且有一些机制可以让您使用 foreach 循环访问子游戏对象。


不幸的是,您不能这样做:foreach (GameObject thisObject in areaContainer)

因为 areaContainer 是一个 GameObject 并且此实现不是针对 GameObject 类完成的。这就是您收到此错误的原因:

foreach statement cannot operate on variables of type 'UnityEngine.GameObject' because 'UnityEngine.GameObject' does not contain a public definition for 'GetEnumerator'

要修复它,请在找到 GameObject 后将循环更改为使用 Transform:

GameObject areaContainer = GameObject.Find("areaContainer");
foreach (Transform thisObject in areaContainer.transform){}

完整代码:

List<GameObject> MediumAreas = new List<GameObject>();

void DefineMediumAreas()
{
GameObject areaContainer = GameObject.Find("areaContainer");
foreach (Transform thisObject in areaContainer.transform)
{
//Check if it contains area
if (thisObject.name.StartsWith("area"))
{
//Add to MediumAreas List
MediumAreas.Add(thisObject.gameObject);
}
}
}

关于c# - 使用 foreach 循环查找作为其他对象的子对象的游戏对象 (Unity3d),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51963368/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com