I’m trying to set points around my level, and every object that is supposed to be spawned goes to that point. Is there something I’m doing wrong with this script? Any help would be grateful. Thanks!
var Objs : Transform[];
var spawnPos : Transform[];
function Start(){
for(var i : int = 0; i < spawnPos.Length; i++){
var thingsToSpawn = Objs.Length;
Instantiate(Objs[thingsToSpawn],spawnPos[i].position,transform.rotation);
}
}
the thingsToSpawn variable is not quite right. If you set it to the length of the array and then try to get that item from the array you’ll get an error. Why? Because an array starts counting at zero. So an array with 3 elements has elements 0, 1 and 2. The length property of this array will give 3 so you are trying to get item 3 from an array with only items 0,1 and 2
If you are trying to get only the last item from the Objs array then you should set thingsToSpawn to Objs.length - 1
That’s hard to answer, because you haven’t been clear with what you’re trying to do. As has already been mentioned, you can’t do this:
var thingsToSpawn = Objs.Length;
// and then reference Objs[thingsToSpawn]
… as that’s trying to access an element that doesn’t exist. If you’re trying to always spawn the last object (which is “close” to the above) you’d want this:
var thingsToSpawn = Objs.Length;
// and then reference Objs[thingsToSpawn - 1]
If you’re trying to spawn the object that’s at the same index as the spawnPos, you’d want this:
Objs[i]
but that means that both the Objs array and the spawnPos must have the same number of elements
If you’re trying to spawn all items in the Objs array at each spawn point, you’d need to create an “inner” loop and spin through the full Objs array for each element of the spawnPos array being accessed in the “outer” loop.
So, it all depends on what result you’re after - which I don’t think you ever mentioned (unless I somehow missed it).
Sorry if I wasn’t clear before, but the Objs was the closest answer I was looking for. What I originally wanted was to place a prefab in a scene and when the game starts, it’ll take that prefab’s starting position, store it, then destroy it, then when ready, It’ll spawn that prefab. It would save the time of positioning empty gameObjects, but what I have is better than what I already have…thank you! Now, it’s just the deal of detecting that the spawned objects are null/collected by the player. I get no error, it just doesn’t Debug the comment: ```
*var Objs : Transform;
var spawnPos : Transform;
function Start(){
renderer.enabled = false;
for(var i : int = 0; i < spawnPos.Length; i++){
Instantiate(Objs[i],spawnPos[i].position,transform.rotation);
}
}
function Update(){
var arrayEmpty : boolean = true;
for (var go : Transform in Objs){
if(go != null){
arrayEmpty = false;
}
}
if(arrayEmpty){
Debug.Log("Spawns Collected!");
}