Instantiating prefab on a tile

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 :

void Update()
    {
        if(Input.GetButtonDown("Interact") && tilemap.GetTile(tilemap.WorldToCell(transform.position)).name.Contains("GrassTile"))
        {
            tilemap.SetTile(tilemap.WorldToCell(gameObject.transform.position), FieldTile);
        }
        else if(Input.GetButtonDown("Interact") && tilemap.GetTile(tilemap.WorldToCell(transform.position)).name.Contains("FieldTile"))
        {
            Instantiate(Plant, transform.position, Quaternion.identity, grid);
        }
    }

Im sure there must be a simple solution to this that im not finding.

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.

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.

spawnPoint = tilemap.GetCellCenterWorld(tilemap.WorldToCell(transform.position));
            Instantiate(Moonfruit, spawnPoint, Quaternion.identity, grid);
1 Like