Random enemy generator

Hello,

*Excuse my rusty English

I’m creating a 2D Game and trying to create a random moving enemy, and the code works fine in small numbers… but when i enter more than 50 enemies the game become very heavy! and i want to create more than 50!! is there another solutions?

using UnityEngine;
using System.Collections;

public class CreateRandomEnemy : MonoBehaviour {
	
	public GameObject enemyPrefab;
	public float numEnemies;
	public float xMin = 6F;
	public float xMax = 50F;
	public float yMin = 2F;
	public float yMax = -8F;
	
	void Start () {
		
		GameObject newParent = GameObject.Find("Scripts");
		
		for (int i = 0; i < numEnemies; i++)
		{
			Vector3 newPos = new Vector3(Random.Range(xMin, xMax), Random.Range(yMin, yMax), 0);
			GameObject octo = Instantiate(enemyPrefab, newPos, Quaternion.identity) as GameObject;
			octo.transform.parent = newParent.transform;
		}
		
	}
}

Without seeing what might be on your enemy prefabs, including scripts, we can assuming creating 50+ gameobjects then is only heavy because of the instantiate call. This is where you may want to look into a pooling system that per-instantiates your game objects to be recycled and reused in your game when it loads.

Boon Cotter has a freebie that does just that. You can also look up Pool Manager in the asset store or around the net, there are plenty of tutorials on creating them.

I would start by implementing the game object pooling system and see if that helps. Otherwise you may want to also investigate the scripts on the enemy game objects to see if they are doing anything silly during Start or Update.