I would like to know how to keep track of instances of prefabs so that I can delete certain instances at certain times from a game master script.
So, I would Instantiate “BallObject” a few times and then be able to delete a certain one of them, say the second to be Instantiated, using a script. Is there a way to create variables that keep track of instances of a prefab as they are created? So var Ball1 is the first ball instantiated, Var Ball2 is the second and so on.
I tried something like this:
var Ball1 : GameObject;
Ball1 = Instantiate (ballPrefab, transform.position, transform.rotation);
I’m guessing that didn’t work because ball1 is a local variable to whatever function it was created in, and you’re calling Destroy(ball1) in a different function? Variable names have to be global in order to be accessed from outside a function.
Also, if you have a number of objects, you’d probably want to use an array of some kind instead of a different variable for each one. If you know beforehand how many objects you want, then use a built-in array:
var ball : GameObject[];
var ballPrefab : GameObject;
function Start() {
ball = new GameObject[10];
for (i = 0; i < 10; i++) {
ball[i] = Instantiate(ballPrefab);
}
}
function DestroyBall(whichOne : int) {
if (ball[whichOne] whichOne < ball.length) {
Destroy(ball[whichOne]);
}
else {Debug.Log ("Attempted to destroy non-existing ball");}
}
That would make 10 balls, and you could destroy the second one by doing “DestroyBall(1);” (keeping in mind that the numbering starts at 0).
You could also use a Javascript array, which provides more flexibility (if, for example, the number of balls varies a lot and you don’t want to specify upfront how many there will be). The downside is that this kind of array is slower, but unless you’re looping through a lot of balls every frame, it probably won’t make a difference.
Thanks for your response, Eric. Actually, both snips of code are from a function Update… But I will play with the code you provided and see how that works. Once again, the answer is in the arrays!