SetActive() not working on pooled objects?
I have a Pool of objects (cars) from which I want to spawn objects at some random intervals. So to choose a random object from the pool, I have a function which chooses a random object, and tries to activate it using SetActive() function. Here is the function.
void ChooseCarToActivate()
{
int randomArg = (int)Random.Range (0, laneCars.Length);
if (!laneCars [randomArg].activeInHierarchy)
{
GameObject temp = laneCars [randomArg];
temp.SetActive (true);
temp.transform.position = transform.position;
temp.GetComponent<ObstacleCarsBehavior> ().SetItActive ();
print (gameObject.name + ": SPAWN" + temp.name);
spawnNow = false;
}
else
{
print ("Choosing again: " + gameObject.name);
ChooseCarToActivate ();
}
}
So, laneCars is the pool array. First the function checks if the currently selected object is already active. If not, it activates it. But, the SetActive(true) ain't working. It doesn't activates the object it is printing. I would really appreciate if can anyone help.
Answer by Socapex · Dec 31, 2015 at 07:42 PM
So, since laneCars is an array of prefabs, you need to Instantiate them. In unity, you can't just enable a prefab, since it doesn't exist. Replace your SetActive line with an instantiate line. Something like Instantiate(temp);
You can set the postition and rotation of instantiated objects to. Think of Instantiate as a constructor (if you are used to other OOP languages). More info http://docs.unity3d.com/ScriptReference/Object.Instantiate.html
Hope this helps :)
But, that's not even the problem. temp.SetActive(true) in the 7th line doesn't seem to work.
The print on the 10th line is being executed, and I can see that output on the console. But the SetActive() function is not activating the gameobjects itself.
Can you post what is laneCars? Is it a list/array of GameObjects dragged from the inspector (guessing here)?
I am a little bit shooting in the dark, as this is quite strange to me. Unless there is something obvious that we are both missing :)
Answer by dakshesh1010 · Jan 01, 2016 at 09:55 PM
laneCars is an array of prefabs. There are few lanes in my game, and each lane is responsible for itself to generate a car at some random intervals (an empty gameObject to control it). There are 5 types of cars (obstacles) in my game. So I created an array of size 10 and populated this array in the inspector randomly by drag and drop for each lane. I hope this gives a better understanding of my problem.
@Socapex Sorry I added it as an answer ins$$anonymous$$d of a comment.
No problem, I edited my answer which should make it work. Unless I really didn't understand the problem.