- Home /
 
Spawning help
I am trying to make a spawn that when i get close a demon appears. the problem is it spawns a billion at once help.
     var Player : Transform;
     var Range : int;
     var prefab : GameObject;
     function Start () {
     }
     function Update () {
     transform.LookAt(Player);
     if(Vector3.Distance(transform.position,Player.position) <= Range){
     Instantiate(prefab, transform.position, transform.rotation);
     }
     }
 
              Answer by Chronos-L · Apr 15, 2013 at 02:37 AM
You need something to control how many demons you want to spawn, and at what interval they will spawn.
Your current code will spawn a demon whenever the player is close enough, and the spawn happens every frame.
One of many ways to fix this
 var Player : Transform;
 var Range : int;
 var prefab : GameObject;
 
 var spawnCount : int = 3;            //How many to be spawn
 var spawnInterval : float = 2.0;     //wait this much of time to spawn new demon
 private var _lastspawnTime : float;  //when the last spawn happen
 
 function Start () {
     _lastspawnTime = -spawnInterval;
 }
     
 function Update () {
     transform.LookAt(Player);
 
     if(Vector3.Distance(transform.position,Player.position) <= Range){
         if( _lastspawnTime < Time.time && spawnCount > 0 ) {
            Instantiate(prefab, transform.position, transform.rotation);
             _lastspawnTime = Time.time + spawnInterval;
             spawnCount--;
         }
     }
 }
 
               There are other ways to do it, but I wouldn't write them down here.
$$anonymous$$y bad, typo error, the script is fix and edited. It should be _lastspawnTime 
Your answer
 
             Follow this Question
Related Questions
Spawn Point 2 Answers
How to spawn enemies at different locations and avoid overlapping each other 2 Answers
How to prevent multiple spawns from a single spawn point? 1 Answer
How to increase the spawn rate of an object over time? 2 Answers
How do I spawn more the one spawnpoints ramdomly in my scene / Spawning problems 0 Answers