Hey guys. I’m trying to randomly spawn enemies on the screen. To do so I’m using System.Random’s Next() method.
Basically what’s happening is that whenever I start up the game in the editor the enemies always spawn in the same position (for me it’s x: 850, y and z: 0). I want the enemies to spawn in different positions. I know creating an instance of System.Random() in the for loop can cause issues like this, but I have my System.Random() instance created in the Start() method. How can I get this to work as intended? Or is it something other than the Random() that might not be working? Obviously there’s some other issues that this code might present, but right now I just want my enemies not all in the same position.
Thanks a ton! Code’s below.
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class Enemy {
public Transform eType;
public int maxOnScreen;
[HideInInspector]
public int onScreen;
public Enemy(){
}
};
public class SpawnController : MonoBehaviour {
public List<Enemy> enemies;
tk2dCamera cam;
System.Random rangeCalc;
// Use this for initialization
void Start () {
cam = tk2dCamera.inst;
rangeCalc = new System.Random();
}
// Update is called once per frame
void Update () {
foreach(Enemy enemy in enemies)
{
EnemyController eScript = enemy.eType.GetComponent<EnemyController>();
if (enemy.onScreen < enemy.maxOnScreen
WhaleController.distance >= eScript.distanceStart)
{
Debug.Log("Spawn!");
spawn ();
}
}
}
void spawn() {
foreach (Enemy enemy in enemies)
{
EnemyController eScript = enemy.eType.GetComponent<EnemyController>();
if (WhaleController.distance >= eScript.distanceStart)
{
for (int i = 0; i < enemy.maxOnScreen; i++)
{
int ePosX = rangeCalc.Next(eScript.minX, eScript.maxX);
ePosX += (int) cam.ScreenExtents.xMax;
int ePosY = rangeCalc.Next(eScript.minY, eScript.maxY);
if (enemy.onScreen < enemy.maxOnScreen)
{
Transform newEnemy = (Transform) Instantiate(enemy.eType, new Vector3(ePosX, ePosY, enemy.eType.position.z), enemy.eType.localRotation);
newEnemy.parent = this.gameObject.transform;
enemy.onScreen++;
}
}
}
}
}
}