- Home /
Spacing objects out when instantiated using variables.
I had trouble with a script earlier that was supposed to spawn an increasing amount of objects. Now the script is almost finished but now I'm having a different problem. From the documentation on instantiating objects there was a method in there that spaced out the objects. namely this:
for(var w : int = 0; w < 10; w++)
{
Instantiate(prefab, Vector3(w * 2, 0, 0), Quaternion.identity);
}
now in my code I have replaced vector 3 with a variable but unity doesn't seem to like this.
var wave_number = 0;
var wave_text : GUIText;
var wave_amount = 5;
var background_timer = 0;
var wave : boolean;
var prefab : Transform;
var spawnpoint : Transform;
private var spawnpoint_location : Vector3;
function Start () {
}
function Update () {
background_timer = Time.time % 11;
if(background_timer == 10)
{
wave = true;
Invoke("New_Wave", 1);
}
}
function New_Wave () {
if(wave)
{
spawnpoint_location = spawnpoint.position;
wave_number++;
wave_amount += 5;
Debug.Log("Wave number is " + wave_number.ToString() + ". " + "There are " + wave_amount.ToString() + " enemies.");
wave = false;
wave_text.text = ("Wave " + wave_number.ToString() );
for(var w : int = 0; w < wave_amount; w++)
{
Instantiate(prefab, spawnpoint_location(w * 2, 0, w * 2), Quaternion.identity);
}
}
}
With the above code I get this error:
Assets/Scripts/wave_spawner.js(35,37): BCE0077: It is not possible to invoke an expression of type 'UnityEngine.Vector3'.
And removing the part in the loop that spawns the NPCs in a spaced fashion gets rid of the error, but when they instantiate they are all on top of each other.
My question is, how can I space the objects out while keeping the location as a variable (with which I can place a GameObject in to manually set a spawn point)?
Answer by aldonaletto · Oct 28, 2012 at 08:57 PM
Calculate spawnpoint_location each iteration, like this:
for(var w : int = 0; w < wave_amount; w++)
{
spawnpoint_location = spawnpoint.position + Vector3(w * 2, 0, w * 2);
Instantiate(prefab, spawnpoint_location, Quaternion.identity);
}
Yep. That took care of the error. Though I wonder why unity doesn't like that I try to space them out in the instantiate function?
You could calculate the position directly in the Instantiate function call as well:
Instantiate(prefab, spawnpoint.position + Vector3(w * 2, 0, w * 2), Quaternion.identity);
The problem with your original code was generated by this expression:
spawnpoint_location(w * 2, 0, w * 2)
This looks to the compiler as a call to a function referenced by spawnpoint_location.