# Spawning help

**URL:** https://discussions.unity.com/t/spawning-help/68640
**Category:** Questions & Answers
**Created:** [April 15, 2013, 2:24am UTC](https://discussions.unity.com/t/spawning-help/68640 "2013-04-15T02:24:39Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![quinn.d40](https://avatars.discourse-cdn.com/v4/letter/q/f9ae1b/32.png) [@quinn.d40](https://discussions.unity.com/u/quinn.d40)
#### Post date: [April 15, 2013, 2:24am UTC](https://discussions.unity.com/t/spawning-help/68640/1 "2013-04-15T02:24:39Z")

</div>

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);
    }
    }

```

---

<div class="post-metadata">

### Author: ![Chronos-L](https://avatars.discourse-cdn.com/v4/letter/c/e36b37/32.png) [@Chronos-L](https://discussions.unity.com/u/Chronos-L)
#### Post date: [April 15, 2013, 2:37am UTC](https://discussions.unity.com/t/spawning-help/68640/2 "2013-04-15T02:37:49Z")

</div>

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.
