- Home /
Cycle and Instantiate from an Array of GameObject
Hi there, I'm trying to create a function that allows (with the mouse click) to instantiate a gameObject from an array... whilst destroying the previous, in other words cycling through an array of gameObjects.
var childObject : GameObject[]; var changeObj : int = 1;
function onScrollChangeObject(){ var newObj = Instantiate(childObject[changeObj],transform.position,transform.rotation); //I want the new object to be the child of this object (with the script) newObj.transform.parent = transform; }
function Update () { if (Input.GetButtonDown("Fire1")){ //Is it possible to use a 'for' loop to do this cycle if(changeObj<2){ changeObj++; } else { changeObj = 0; } onScrollChangeObject(); }
This instantiates from an array, but I can't work out how to Destroy the previous
Answer by Cyb3rManiak · Apr 27, 2011 at 11:59 AM
Instantiate returns a reference to the instantiated object. As long as you have only one object alive at each given time you can save that reference in order to destroy it, and do something like this:
var childObject : GameObject[]; var changeObj : int = 1; var currObjAlive: GameObject;
function onScrollChangeObject() { // If there is already an object alive- destroy it if (currObjAlive) Destroy(currObjAlive);
currObjAlive = Instantiate(childObject[changeObj],transform.position,transform.rotation);
//I want the new object to be the child of this object (with the script)
currObjAlive.transform.parent = transform;
}
function Update () { if (Input.GetButtonDown("Fire1")) { //Is it possible to use a 'for' loop to do this cycle if(changeObj<2){ changeObj++; } else { changeObj = 0; } onScrollChangeObject(); }
BTW - a nifty trick to use in situation where you have an array and you want to iterate over it using the index and loop is:
if (Input.GetButtonDown("Fire1"))
{
changeObj = (changeObj + 1) % 2;
onScrollChangeObject();
}
That little trick is something i've been needing for ages! and that solution worked perfectly. Thankyou!
Small side note: ins$$anonymous$$d of going crazy saving the instantiated object reference just do oldObject = newObject; newObject = Instantiate(stuffz). Now you can destroy the old object or do.. what ever. ;)