Hi guys,
I’m having some trouble with spawning from an array I have it working almost perfectly however every now and again it spawns 2-4 objects when it should only spawn one, anybody got any ideas why this happens? Heres my scripts:
static var spawningMap: boolean = false;
var objectsToSpawn: GameObject[ ];
function FixedUpdate()
{
//check if spawning item
if(spawningMap == true)
{
spawnMap();
}
}
function spawnMap()
{
//spawns objects from array
var thingToSpawn: int = Random.Range(0, objectsToSpawn.length);
Instantiate(objectsToSpawn[thingToSpawn], transform.position, transform.rotation);
}
var speed: int = 80;
function Update()
{
var amtToMove = speed * Time.deltaTime;
transform.Translate(Vector3.back * amtToMove,Space.World);
if(transform.position.z < -250)
{
Destroy (gameObject);
}
if(transform.position.z <= 101.443)
{
SpawnControllerMap.spawningMap = true;
}
else if(SpawnControllerMap.mapSpawned == true)
{
SpawnControllerMap.spawningMap = false;
}
}
Any help would be appreciated.
Thanks
I’m guessing you want to spawn once per frame. If the problem is that you get multiple spawns per frame, I am going to say your problem is putting the spawning code inside FixedUpdate() which can run multiple times a frame. Sometimes FixedUpdate() will not even run in a frame.
This is because FixedUpdate() occurs when the physics is updated, and Update() happens when the screen is updated. These do not happen at the same time.
I do not see any physics happening so the fix would be to put everything inside Update() and get rid of the FixedUpdate().
You need to stop your condition in the Update function from setting that static var more that once. Hook up a Debug or print line in your conditions to troubleshoot what is true more than once.
I like to use a simple int to stop a condition
(eg)
if((something<=something)(someInt==0)) {
someInt = 1; //Upper condition is now locked till reset
//Then the code to be called once
}
There’s a little mistake in the else if, I amended it here thats what it says still getting the same error. If I use just the Update function instead of just spawning 1 it always spawns 2 pieces, I will have to give the other thing a try with the int hanks for the help, anymore help would be appreciated
else if(SpawnControllerMap.spawningMap == true)
{
SpawnControllerMap.spawningMap = false;
}