Search Unity

Static platform spawn at a fixed position if it spawn first

Discussion in 'Scripting' started by Keiji1, Oct 22, 2021.

  1. Keiji1

    Keiji1

    Joined:
    Jul 8, 2021
    Posts:
    4
    I make this script to spawn 2 prefabs in my game using a list of arrays. So to sum up the problem that I have right now is that I wanted my first prefabs (1st array object) on a static platform if it is the first object getting spawned when the game started it should spawn at a fixed x-axis coordinate if not then it should spawn randomly afterward.

    Code (CSharp):
    1. float dirY;
    2.     public Platform[] prefabs;
    3.     public GameObject Player;
    4.     bool spawnEdit;
    5.     int random;
    6.     bool isFirstObject;
    7.     // Start is called before the first frame update
    8.     void Start()
    9.     {
    10.         dirY = -1.1f;
    11.     }
    12.  
    13.     // Update is called once per frame
    14.     void Update()
    15.     {
    16.         if (Player.transform.position.y < dirY && !spawnEdit) {
    17.             for (int i = 0; i < 5; i++)
    18.             {
    19.                 random = Random.Range(0, prefabs.Length);
    20.                 GameObject Spawn = GameObject.Instantiate(prefabs[random].gameObject);
    21.                 //if (random == 0)
    22.                 //{
    23.                 //    Spawn.transform.position = new Vector2(1.5f, dirY);
    24.                    
    25.                 //}
    26.                 if(random == 0)
    27.                 {
    28.                     Spawn.transform.position = new Vector2(Random.Range(-1.5f, 1.5f), dirY);
    29.                    
    30.                 }
    31.                 else
    32.                 {
    33.                     Spawn.transform.position = new Vector2(0, dirY);
    34.                    
    35.                 }
    36.             dirY += 1f;
    37.                 Debug.Log(Player.transform.position.y+ " " + dirY);
    38.            }
    39.             spawnEdit = true;
    40.         }
    41.         else if (Player.transform.position.y > dirY-2) {
    42.             spawnEdit = false;
    43.         }
     
unityunity