I am trying to develop a system of randomly spawning enemies in an infinite runner. So, here is the process in which I am going to spawn the enemies. I am going to choose a time interval at which the enemy is spawned at based on difficulty. (time between each enemy spawning gets shorter as the infinite runner game goes on. Then I am going to randomly choose the distance apart the enemy will spawned at based on difficulty. Then choose from 4 different enemy choices. What I just explained is my grand, master plan, but I am still trying to just spawn one enemy let alone all 4. I have been reading all about prefabs, instantiation, object pooling, and reusing objects. What I have learned is that instantiation and destroying objects can be expensive, but so can object pooling at times. I am 13 years old and I have just begun developing in Unity so object pooling from what I can see is a pretty complex topic. You are probably more experienced than me so, what do you think is the best path to go down for what I am trying to do? This is not a write-me-the code question, it is just asking what path I should follow to spawn the enemies. Here is the code I have so far which generates enemies but gets to a point where the game gets so slow, it is unplayable.
public Transform garbagePile;
private float randomeTimeInterval;
private float randomXDistance;
private float lastXValue;
private int randomZPos;
private float[] randomZValues;
private float theZValue;
private int numOfGarbage;
// Use this for initialization
void Start() {
CreateEnemy ();
randomZValues = new float[3];
randomZValues [0] = 0.0f;
randomZValues [1] = -2.0f;
randomZValues [2] = 2.0f;
}
void CreateEnemy () {
randomXDistance = Random.Range (6, 9);
randomZPos = Random.Range (0, 3);
theZValue = randomZValues [randomZPos];
Vector3 pos = new Vector3((float)lastXValue + randomXDistance,0,(float)theZValue);
Instantiate(garbagePile, pos, Quaternion.identity);
lastXValue = garbagePile.transform.position.x;
}
// Update is called once per frame
void Update () {
Vector3 updatePos = new Vector3 ((float)0.2, 0, 0);
garbagePile.transform.position -= updatePos;
if(garbagePile.transform.position.x <= (float)-11){
Destroy(gameObject);
CreateEnemy();
}
}
}
↧