Search code examples
unity-game-enginespawn

How to create spawner in a row in unity


I want to spawn 3 object horizontally and I want to spawn them randomly (for example in first spawn if blue is in the middle next it will be get positioned randomly and the other same as this one)
enter image description here

And here is the code I have now:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemySpawner : MonoBehaviour {

public float min_X = -2.3f, max_X = 2.3f;

public GameObject[] colorobject;


public float timer = 2f;

void Start() {
    Invoke("SpawnObject", timer);
}

void SpawnObject() {

    float pos_X = Random.Range(min_X, max_X);
    Vector3 temp = transform.position;
    temp.x = pos_X;

    if(Random.Range(0, 3) > 0) {

        Instantiate(colorobject[Random.Range(0, colorobject.Length)],
        temp, Quaternion.identity);
        
    } else {

       //
        
    }

    Invoke("SpawnObject", timer);

}



} // class

Solution

  • You can try to have a random integer value and a range. For example, if I decide the range between 0-6,if my number is between 0 and 1, I will spawn Red-Blue-Green;if it is between 1 and 2, I will spawn Red-Green-Blue. This may not be the best approach but the only one I can think of right now. You can use Random.Range for that as you have used it above :D