[英]Turning off multiple game objects at once in Unity
I'm wanting to turn off multiple game objects and all their associated children at once with a single method call. 我想通过一个方法调用一次关闭多个游戏对象及其所有关联子对象。
My thinking behind this was to create a list to hold all of the game objects I want to deactivate and pass all those objects in. However, I'm trying to implement the actual SetActive
method call with my list and Im running into some issues. 我在此背后的想法是创建一个列表,以保存要停用的所有游戏对象并将所有这些对象传递给其中。但是,我试图用列表实现实际的
SetActive
方法调用,而Im遇到了一些问题。
Here is my code just now: 这是我现在的代码:
public List<GameObject> deactivate_Screen = new List<GameObject>();
void OnClick()
{
for( int i = 0; i < deactivate_Screen.Count; i++)
{
deactivate_Screen.SetActive(false);
}
}
Now the obvious reason this isn't working is clear to me. 现在,这显然不起作用的明显原因对我来说很清楚。 A list can't access to the SetActive function I'm trying to achieve.
列表无法访问我试图实现的SetActive函数。 However, I'm at a loss to implement the functionality I require.
但是,我不知道要实现所需的功能。
Could someone please show me what I need to do, or point me in the right direction to fix my error? 有人可以告诉我我需要做什么,或者为我指出正确的方向来纠正我的错误吗?
As you correctly recognized, SetActive
is a method of a GameObject
, not of the List<GameObject>
. 如您正确认识到的那样,
SetActive
是GameObject
的方法,而不是List<GameObject>
。
You have to invoke SetActive
in each iteration for the game object the index i
of the current iteration refers to - you can access that object with the List<T>
indexer , ie by placing square brackets with the index behind deactivate_Screen
. 您必须在每次迭代中为当前迭代的索引
i
所指的游戏对象调用SetActive
您可以使用List<T>
索引器访问该对象,即,将带有索引的方括号放在deactivate_Screen
。
Thus, the "current item" in each iteration is deactivate_Screen[i]
, hence your loop should look as follows: 因此,每次迭代中的“当前项目”是
deactivate_Screen[i]
,因此您的循环应如下所示:
for (int i = 0; i < deactivate_Screen.Count; i++)
{
deactivate_Screen[i].SetActive(false);
}
Just replace 只需更换
deactivate_Screen.SetActive(false);
to 至
deactivate_Screen[i].SetActive(false);
As List
itself is not a game object but its elements are List[0] List[1] List[2] List[3].....
因为
List
本身不是游戏对象,但其元素为List[0] List[1] List[2] List[3].....
In your loop you need to access the element of the list at the index i : 在循环中,您需要在索引i处访问列表的元素:
for( int i = 0; i < deactivate_Screen.Count; i++)
{
deactivate_Screen[i].SetActive(false);
}
or using a foreach loop 或使用foreach循环
foreach (var gobj in deactivate_Screen)
{
gobj.SetActive(false);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.