I have a C# script(for and android game) that should spawn an object at a random position on the x axis between -50 and 50 ONCE, but it does neither at the minute. I get a constant stream of coins spawning in, when I just want one, and also, they are all in the same location. I don’t get any errors, and cannot work out what is wrong with my script.
using UnityEngine;
using System.Collections;
public class Spawner : MonoBehaviour {
public bool spawn;
public Transform coin;
public Vector3 pos;
void Start()
{
pos = new Vector3(Random.Range(-50.0f, 50.0f), 50, 0);
spawn = true;
}
void Update()
{
if(spawn = true)
{
GameObject instance = Instantiate(coin, pos, transform.rotation) as GameObject;
spawn = false;
}
}
}
You get constant stream of coins spawning because you use Instantiate inside Update(). So Instantiate gets called in every frame. You must use Instantiate in a separate method, and call it from Update when, for example, a key is pressed (in the code below I use the space key to spawn). Also, the Random function must be called just before Instantiate, and not just once in Start().
e.g.
using UnityEngine;
using System.Collections;
public class Spawner : MonoBehaviour {
public Transform coin;
public Vector3 pos;
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Spawn()
}
}
void Spawn()
{
pos = new Vector3(Random.Range(-50.0f, 50.0f), 50, 0);
Instantiate(coin, pos, transform.rotation) as GameObject;
}
}
Secondly, after making this change you will notice that only one object will ever spawn, and that’s it. Somewhere in your code you need to change ‘spawn’ to == TRUE. So, let’s add a simple timer.
// add these members to your class
float theTime;
int spawnDurationSeconds = 3; // number of seconds between each spawn
// In your Start method let's set the time to NOW
theTime = Time.time;
//In your Update method, place this above your 'IF spawn == true' statement
if(Time.time - theTime > spawnDurationSeconds * 1000) {
spawn = true;
theTime = Time.time; // reset the time
pos = new Vector3(Random.Range(-50.0f, 50.0f), 50, 0); // randomize the position
}
Thank you for all your answers. I can’t believe that I missed two obvious mistakes. I have turned off my computer now, and i’ll post again if it doesn’t work. But I’m sure that won’t be necessary. Thanks again!