How to fix my enemy Instantiate script? its clone too many

Hi Guys,

I’m trying to make my enemy come out from either left & right screen. And I attached this script to my enemy.

var speed:int = 1;
var enemyslot:GameObject;

function Update () {
    	transform.position.x -= speed * Time.deltaTime;
		if(transform.position.x > 6.1 || transform.position.x < -6.1)
		
		{
			Instantiate(enemyslot: transform.position,   Quaternion.identity);
	 		transform.position.x = -7 || 7 ;
   			transform.position.y = Random.Range(-2.3, 1.4);
			transform.position.z = -3;
		}
}

1a)) when it tested play, the enemy move out of the screen, it created too many till unity crashed.
So how do i add spawn, limiter or time to fix that?

1b) any other advices? like should i put it inside another script or something?

  1. In this game object (inside a prefab), i created a enemyslot gameobject, then i drag its own prefab to it, so for my Instantiate.

How do I work around without having to create a gameobject slot & put itself under its own gameobject slot to Instantiate?

Thanks in advance!

To add a spawn limiter, just set up a count with a for loop, and for question 2, I believe you want a GameObject.Find?

var speed: int = 1;
var enemySlot : GameObject;
var spawnLimit : int;
private var canPos : boolean = true;

function Update () {
		
	transform.position.x -= speed * Time.deltaTime;
	
	if(transform.position.x > 6.1 || transform.position.x < -6.1) {
        for (var count = 0; count < spawnLimit; count++) {
        	if (count <= spawnLimit) {
        		var enemyInst : GameObject = Instantiate(enemySlot, transform.position, Quaternion.identity) as GameObject;
        		canPos = true;
        		if (canPos) {		//I am just setting up a boolean flag so that the position doesn't jump everywhere with Random.Ranges
        			enemyInst.transform.position = Vector3(Random.Range(-7, 7), Random.Range(-2.3, 1.4), -3);
        			canPos = false;
        		}
        	}
		}
	}
}

I’m pretty sure that should work.

Hope that helps, Klep

function spawn()
{
var time : int = Time.realtimeSinceStartup * 1000;
if((time & 0x01) == 0) //Checking if the time millisecond count is an even number(To make it come out of random side)
{
Instantiate(enemyslot, spawn1.transform.position, Quaternion.identity);
}
else
{
Instantiate(enemyslot, spawn2.transform.position, Quaternion.identity);
}
}
When you call this function it will spawn 1 enemy in one of the spawns.
It needs 3 variables - enemyslot – this will be the enemy, spawn1 and spawn2 – these are the spawns.

I answered a question about enemy spawning some time ago, where the enemies were being created by dozen without any limit. Maybe the answer can help you - take a look at Spawing Enemies works but works to good - Questions & Answers - Unity Discussions