I am currently trying to create a reference variable so I can set particular GameObjects active/inactive. Here’s what I’ve got so far.
(in the Start method)
currentObj = GameObject.Find(“/TheGenerator/00”);
(in the Update method)
if (var > 10) {
currentObj.SetActive(false);
currentObj = GameObject.Find(“/TheGenerator/00”);
currentObj.SetActive(true);
}
Obviously this doesn’t work, but does anyone know to make this in a way that would work?
Normally you can’t find an inactive object but u have two options:
Options 1:
u can use tags and add tags to every object created and then activate the object by tag (but it’ll cost a little bit of work). or u can use option 2.
Option 2: (the one I used thinking it suited you and easier)
you search for every single object present and if the object has the name you are looking for, you make it active.
below you find the script corrected by me with the second option and with further explanations.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class FindAndActiveAnInactiveObject : MonoBehaviour
{
public GameObject Generatedobject;
public int DeleteGenerated;
GameObject[] objects;
bool StopSwitch; //bool to stop the finding inactive object error in update
void Start()
{
for(int i = 0; i<10; i++) //creating objects to test
{
Generatedobject = new GameObject($"Generatedobject{i+1}");
}
Generatedobject = GameObject.Find("Generatedobject10");
Generatedobject.SetActive(false);
}
void Update()
{
if (DeleteGenerated > 10 &&StopSwitch == false) //the bool StopSwitch will prevent from giving u error trying to finding the inactive object "Generatedobject1"
{
Generatedobject = GameObject.Find("Generatedobject1");
Generatedobject.SetActive(false);
objects = Resources.FindObjectsOfTypeAll<GameObject>(); //to use the function FindObjectsOfTypeAll u need to add using System.Linq; on top
for (int i =0; i<objects.Length; i++) //scroll through the object array to find the object with the name you are looking for
{
if (objects*.name == "Generatedobject10") //name of the inactive object that u want activate*
Generatedobject = objects*;*
}
Generatedobject.SetActive(true);
StopSwitch = true;
}
}
}