How can I activate many GameObject with a single button / script?
Hello! I have a problem with the project I'm working on. I have a list of 20+ GameObject, which I want to activate with a single button / script. I could use for each GameObject, this method: GameObject.SetActive (true); , but the problem is that more objects will appear. Much more than 20. (I mean, I will do more) I searched and tried all (almost all) solutions on the internet, but none of them worked ... I tried with Tags ... Can you help me, please? Below is one of the options I used ....
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class ActivateTags : MonoBehaviour { public GameObject[] cpus;
public void Activatei3()
{
cpus = GameObject.FindGameObjectsWithTag("i3tag");
foreach (GameObject cpu in cpus)
{
cpu.SetActive(false);
}
}
[1]: /storage/temp/183166-screenshot-2021-07-07-231036.png
Answer by starviw · Jul 08, 2021 at 03:10 AM
As stated in the documentation, FindGameObjectsWithTag returns an array of active game objects that uses that tag. Thus, if you have more than intended, that means you have more objects using that tag.
There are multiple ways to get a specific list of objects. From the top of my head, there are 2 ways to get them
1. use FindObjectsOfType if the list of game objects uses a specific script
2. place the script on the head of the list of game object and use GetComponentsInChildren to get all the game objects beneath it.
note that you should use all the stated functions in start and save it as a variable and just loop through them when you click on the button if you are not spawning the objects dynamically, as all these functions are heavy in running.
also, to set a game object to be active, SetActive(true) is definitely the right way. using false will deactivate it.
Thanks for the help! I will consider what you told me. After I asked the question, you searched me a bit on the internet and found a solution. (I know that .SetActive (false) = disabled; (true) = enabled, in the script above I tried to see if it works to deactivate the objects, considering that it didn't work to activate, and I copied it like this ... ) :))
Anyway, thanks for the help!
Your answer
Follow this Question
Related Questions
Why can't you add editor scripts to GameObjects even if the tag is EditorOnly? 0 Answers
How to access an inactive gameObject with tag 2 Answers
instantiate prefab at every gameobject with tag 0 Answers
Stop a game object from following an untagged object. 1 Answer
How to become invincible towards enemies when powerup is active 2 Answers