Spawning issues
okay so im trying to spawn some targets for my little guy to shoot. and when ive put my code in, he gets rained on by targets instead of them dropping in and fading away (also getting a strikeout error for line 7 ). Any help would be a bonus. cheers :)
using UnityEngine; using System.Collections;
public class GameController : MonoBehaviour {
public GameObject target;
float spawnRate = 3;
float lastSpawn = 0;
float currentScore = 0;
public void TargetDestroyed()
{
// Increment score by one for each target destroyed
currentScore ++;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
// Get a random spawn position on the x axis
Vector2 spawnPosition = new Vector2(Random.Range(-17.0f, 17.0f), 10);
// Instantiate a target at the spawn position
GameObject targetRef = Instantiate (target, spawnPosition, Quaternion.identity) as GameObject;
// Set the last spawn time to current time
lastSpawn = Time.time;
Destroy(targetRef, 10); // Destroy after 10 seconds
}
}
Answer by haiderInUnity · Jan 31, 2016 at 12:42 PM
Update() is called once per frame thats why your target is being created every frame which is why its raining. If you want to control the timing of spawn targets you should use coroutines. You can use them like this:
void Start() {
StartCoroutine(Spawn());
}
public IEnumerator Spawn() {
while (true) {
// Get a random spawn position on the x axis
Vector2 spawnPosition = new Vector2(Random.Range(-17.0f, 17.0f), 10);
// Instantiate a target at the spawn position
GameObject targetRef = Instantiate (target, spawnPosition, Quaternion.identity) as GameObject;
yield return new WaitForSeconds(delayTime);
}
}
here delayTime is the time you want to wait for the next spawn to occur. This way you can exactly control how many targets you want to spawn. @harkensaw
Your answer
Follow this Question
Related Questions
Keep the players position constant between two different levels 1 Answer
Instantiate not working correctly (Please help!) 1 Answer
Checking collision before instantiating prefab 0 Answers
Check to see if the new spawn location is different than the previous one? 1 Answer
platforms spawning towards my player 0 Answers