- Home /
Instantiate Prefab Array with ID
Hi there, i run into a problem with instantiating. I'll try to make it short. This is my code:
//Array of GameObjects to hold the vehicles to instantiate
public GameObject[] vehicle;
//Index to give an unique id to the instantiated prefabs e.g mycar_1,mycar_2,mycar_3 etc.
private int[] index = {0};
And then i do the following
//To pick up random prefabs in the array
int rand = Random.Range(0,2);
if ( rand == 0){
//reference to my instantiated gameobject || Cast transfrom to gameobject since Instantiate() returns a transform but i want gameobject || Pick up first element in array position it where my player car is..
GameObject spawnVehicle = (GameObject)Instantiate(vehicle[0],player.transform.position+new Vector3(0,1,50), Quaternion.identity);
//Give it an unique name so my first prefab has the name MyFord which will turn into MyFord_0,MyFord_1 etc. after this line
spawnVehicle.name = vehicle[0].name + "_" + index[0];
//Increment index self explanatory
index[0] +=1;
}
This works perfect and i really achieve what i want to do but doing the same for the next GameObject in the vehicle array is ridiculous.
Now when i do the following:
if ( rand == 1){
GameObject spawnVehicle = (GameObject)Instantiate(vehicle[1],player.transform.position+new Vector3(0,1,50), Quaternion.identity);
spawnVehicle.name = vehicle[1].name + "_" + index[1];
index[1] +=1;
}
This returns not a prefab with an unique ID like it does with the first element in the Array, it just instantiates clones. The question is why? Am i missing something or what did i wrong? The big problem i dont understand is that when it works for one then shouldnt it work also for all the other vehicles in my Array??
Thanks for any help or clue.
Can you write out everything you need the script to do, the way you have attained it is a bit convoluted and if you write out the requirements I can help you understand an alternative way to tackle the problem.
Ok, so im trying to make a little car game. The player just tilts the phone to control the car. While driving I want to instantiate other vehicles that moves towards the player and the player himself must take care not to crash. So far i managed it, and i also can instantiate the vehicles,move them etc.. The problem ive is that i cant handle it with a list or array or whatever.Becuase then outputs a NULLREFERENCE EXCEPTION. I use array because there are different types of vehicles all appearing randomly.
Or what do you suggest me to do? Write extra code for every single prefab? Doing so is ineffective.
Answer by sacredgeometry · Aug 10, 2013 at 12:33 PM
EDIT: I have added more robust error handelling
Here is how I would do it
public class CarSpawner : MonoBehaviour {
public GameObject[] cars;
private int carCounter = 0;
private int curIndex;
void Update () {
// You can add additional tests also I would enclose the instantiation inside a method then that would probably be useful as you could then call it from other places
if(cars.Length != 0 && cars[curIndex] != null){
curIndex = Random.Range(0, cars.Length);
GameObject currentCar = (GameObject)Instantiate(cars[curIndex], Vector3.zero, Quaternion.identity);
currentCar.name = string.Format("Whatever you want to call the car_{0}", carCounter);
carCounter++;
}
}
}
The reason for the null reference exception was either because you were calling the instantiation on objects that didnt exist or because your the index you were generating with Random.Range() was out of the range. I have tried to add some defensive error handling for you.
Basically how this works is that if the array isnt empty it creates a new car object from a random one in the array(you will have to replace the position with where/however you want it to spawn)
I would recommend either tagging these cars with some sort of universal car tag or parenting them to an empty game object.This would allow you to select all of the cars and will avoid your hierarchy panel from getting inundated with spawned objects.
If you want to be able to differentiate between types of car you can do that based on the index in which they are placed ie. any car spawned at index 0 will always be the same model so if you want to tag it in a different way after instantiation you can :)
I hope that helps
Nice! That solved it. Guess the issue i had was the string.Format thing. BIG THAN$$anonymous$$S :D
it helped indeed. $$anonymous$$ost of the stuff you said im doing already. The nullreference exception was because it couldnt find the gameobject which was named for example "myvehicle(clone)". Thus it didnt give thos gameobjects the id I wanted but now it works. Thank for the additional error handling. You are welcome
Answer by cdrandin · Aug 09, 2013 at 10:03 PM
The code is very messy, but her is what I would do to spawn objects using an array.
// Place your prefabs or objects into the array in the inspector.
// You can adjust the index to add more into it.
GameObject[] stuff;
void Start ()
{
for GameObject i in stuff // this is pseudocode
{
// spawns all objects in stuff in the center of the world.
Instantiate(i,Vector3(0,0,0),i.identity)
}
}