- Home /
Script Instantiates only one platform?
I have 5 quads with a spawn script that spawns 3 types of platforms. So in total there are 5 platforms. My problem is that in the update method when reinstantiate is equal to true, it only instantiates 1 platform instead of 5. (so there are 6 when there should be 10). Here's the script: using UnityEngine; using System.Collections;
public class EMplatformSpawn : MonoBehaviour {
public GameObject[] Pobj; // P for platform
public static bool reinstantiate = false;
void Start () {
Pspawn ();
}
// Update is called once per frame
void Pspawn ()
{
Instantiate(Pobj[Random.Range(0, Pobj.GetLength(0))], transform.position, Quaternion.identity);
}
void Update()
{
if (reinstantiate == true)
{
Pspawn();
reinstantiate = false;
}
}
}
Thanks in advance! :)
Answer by RudyTheDev · Dec 25, 2014 at 06:41 PM
The first time Update()
in one of the 5 scripts runs, it sets reinstantiate
to false
. So the other 4 scripts fail the if (reinstantiate == true)
check. You would only ever see 1 platform spawn, as you describe.
You need some mechanism that allows all 5 scripts to spawn without resetting the global flag and without processing it more than once. There are very many ways to do this from simple to complex, reliable to error-prone, etc.
A simple way would be:
public static int reinstantiateFrame = -1;
void Update()
{
// If the next spawning is scheduled for this frame, spawn
if (reinstantiateFrame == Time.frameCount)
{
Pspawn();
}
}
Then set reinstantiateFrame = Time.frameCount + 1;
. (There is no guarantee of script Update()
order, so I had to put spawning on the next frame. You can also set it to current frame if you spawn in LateUpdate()
.)
Your answer
Follow this Question
Related Questions
Using multiple yields in a Coroutine 1 Answer
Distribute terrain in zones 3 Answers
GameObject instantiates too many objects in update 2 Answers
Multiple Cars not working 1 Answer
Refrencing Instantiated Object 1 Answer