Reputation: 2724
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.
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. 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?
Upvotes: 0
Views: 2241
Reputation: 20731
As you correctly recognized, SetActive
is a method of a GameObject
, not of the 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, i.e. by placing square brackets with the index behind deactivate_Screen
.
Thus, the "current item" in each iteration is deactivate_Screen[i]
, hence your loop should look as follows:
for (int i = 0; i < deactivate_Screen.Count; i++)
{
deactivate_Screen[i].SetActive(false);
}
Upvotes: 3
Reputation: 2555
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].....
Upvotes: 1
Reputation: 15941
In your loop you need to access the element of the list at the index i:
for( int i = 0; i < deactivate_Screen.Count; i++)
{
deactivate_Screen[i].SetActive(false);
}
or using a foreach loop
foreach (var gobj in deactivate_Screen)
{
gobj.SetActive(false);
}
Upvotes: 0