Hello!
I have around 10 prefab objects and I want their X position to be random. It’s a game where you have to avoid them so I try to change their X position in the Start function, but they change their position in the same time so rand.Next(-1,2) will generate the same value for all of them, and all of them (prefabs) have the same X position. What can I do so they have different X position?
This is my code:
using UnityEngine;
using System.Collections;
public class GM2enemyStart : MonoBehaviour
{
void Start()
{
System.Random rand = new System.Random();
float px = rand.Next(-1, 2);
float py = 28.809f;
transform.position = new Vector3(px, py, transform.position.z);
}
}
Vector3[] Spawns;
public GameObject[] Zombies;
void Awake()
{
Spawns = new Vector3[Zombies.Length];
for (int i = 0; i < Spawns.Length; i++) {
Spawns [i] = new Vector3 (Random.Range (-300, 300), 1, Random.Range (-300, 300));
}
}
void Start ()
{
Spawn ();
}
public void Spawn(bool randomAmount = true)
{
if (randomAmount) {
if (Zombies.Length > 0) {
for (int zombie = 0; zombie < Random.Range (1, Zombies.Length); zombie++) {
GameObject z;
z = Instantiate (Zombies [zombie], Spawns [zombie], Quaternion.identity) as GameObject;
z.transform.SetParent (transform);
}
}
}
}
so it’s really simple, what my script does is create a Vector3 array of Random spawn positions based on how much prefabs you have (10), so it will create 10 random spawn points in the Awake Function.
What the Spawn() function does is spawns a random amount of zombies (or whatever it is your dealing with) as a child of the GameObject the script is attached to (for example: ZombieManager, all zombies will be spawned as a child of this object) and Instantiates each of them at a its random position chosen in the Awake function
1 Like