Search Unity

Instantiating prefab on a tile

Discussion in 'Getting Started' started by killerKeks26601, Mar 17, 2021.

  1. killerKeks26601

    killerKeks26601

    Joined:
    Jan 13, 2021
    Posts:
    31
    Hello,
    I am having a bit of trouble instantiating a prefab on a tile cell position.
    I am working on a farming game and i want to instantiate a plant prefab on the field tile the Player is standing on.
    I tried to parent the grid while instantiating but that just spawns the plant right under the player.
    I want it to snap to the middle of the cell.
    Here is my code :
    Code (CSharp):
    1. void Update()
    2.     {
    3.         if(Input.GetButtonDown("Interact") && tilemap.GetTile(tilemap.WorldToCell(transform.position)).name.Contains("GrassTile"))
    4.         {
    5.             tilemap.SetTile(tilemap.WorldToCell(gameObject.transform.position), FieldTile);
    6.         }
    7.         else if(Input.GetButtonDown("Interact") && tilemap.GetTile(tilemap.WorldToCell(transform.position)).name.Contains("FieldTile"))
    8.         {
    9.             Instantiate(Plant, transform.position, Quaternion.identity, grid);
    10.         }
    11.     }
    Im sure there must be a simple solution to this that im not finding.
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    The second parameter to Instantiate is the position. You're passing transform.position; I'm guessing this script is on the player, so that would put it at the player position. If you want it at the position of the grid object instead, use grid.transform.position.
     
  3. killerKeks26601

    killerKeks26601

    Joined:
    Jan 13, 2021
    Posts:
    31
    Thanks,
    but that instantiates the prefab on the pivot point of the grid game object instead of the tile.
    I use this code now which works fine for me.
    Code (CSharp):
    1. spawnPoint = tilemap.GetCellCenterWorld(tilemap.WorldToCell(transform.position));
    2.             Instantiate(Moonfruit, spawnPoint, Quaternion.identity, grid);
     
    JoeStrout likes this.