Search Unity

Question Why is this for loop not changing the X position to instantiate objects?

Discussion in 'Scripting' started by BioEnchanted, Feb 11, 2024.

  1. BioEnchanted

    BioEnchanted

    Joined:
    Jan 13, 2024
    Posts:
    22
    I'm trying to use this for loop to instantiate tiles that are a single unit wide. The idea is

    for each x between 0 and 5, the position will be x, 0, 0. So the first iteration the x would equal 0, the second iteration it would equal 1, and so on until the last object is placed at 5, 0, 0. However, it's not changing the x parameter for the objects so they all spawn on top of each other at 0, 0, 0. How can I fix this?

    I'm hoping to have a button that the player can press that will spawn tiles in a x by z grid, like 5 by 5, or 5 by 10,so the plan was to use nested for loops. to instantiate the tiles at the correct positions.

    Alternatively, is there a better way to achieve what I'm attempting to? I have saved the tile as a prefab and dragged it onto the script and it does spawn 5 tiles, they just all spawn on the same spot.

    Code (CSharp):
    1. public class LoadTiles : MonoBehaviour
    2. {
    3.     // Start is called before the first frame update
    4.     public GameObject tile;
    5.     public int xMaxCoord = 5;
    6.     public int zMaxCoord = 5;
    7.     public int xCurrentCoord;
    8.    
    9.    
    10.     void Start()
    11.     {
    12.         for (int x = 0; x < xMaxCoord; x++)
    13.         {
    14.             xCurrentCoord = x;
    15.             transform.position = new Vector3 (xCurrentCoord, 0, 0);
    16.             Instantiate(tile, tile.transform.position, tile.transform.rotation);
    17.         }
    18.     }
     
  2. JoshuaMcKenzie

    JoshuaMcKenzie

    Joined:
    Jun 20, 2015
    Posts:
    916
    transform.position is the position of the gameobject the current script is running on. You are moving the script's gameobject 5 times. You are referencing a Tile gameobject (I assume is a prefab) and just spawning a copy of the Tile at the same location where the original tile is, 5 times.

    try this:
    Code (CSharp):
    1.         for (int x = 0; x < xMaxCoord; x++)
    2.         {
    3.             xCurrentCoord = x;
    4.            var newPosition = new Vector3 (xCurrentCoord, 0, 0);
    5.             Instantiate(tile, newPosition , tile.transform.rotation);
    6.         }
    This should create 5 tiles from {0,0,0} to {4,0,0} (remember x counts up to and stops just before xMaxCoord, not at xMaxCoord). if you want the last tile on {5,0,0} then you want 6 tiles and the for loop should be
    Code (CSharp):
    1. for (int x = 0; x <= xMaxCoord; x++)
     
  3. BioEnchanted

    BioEnchanted

    Joined:
    Jan 13, 2024
    Posts:
    22
    Thank you, I had a feeling it was something very silly.