Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Copying a Tilemap with Script

Discussion in 'Scripting' started by The_wARmAcH1n3, Oct 6, 2023.

  1. The_wARmAcH1n3

    The_wARmAcH1n3

    Joined:
    Aug 5, 2023
    Posts:
    26
    My goal I have written it here:
    https://forum.unity.com/threads/a-2d-platformer-map-to-be-repeating-and-having-no-borders.1501334/

    I want to copy a Tilemap with script and set the clone on the right side, but when I do this, there is only one single Tile duplicated but not the whole Tilemap.

    My Code is:
    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using static UnityEngine.UI.Image;
    6. using UnityEngine.UIElements;
    7. using UnityEngine.Tilemaps;
    8.  
    9. public class GroundTilemapScript : MonoBehaviour
    10. {
    11.     public GameObject tileMapGameobjectOrigin;
    12.     protected GameObject tileMapGameobject;
    13.     protected Tilemap tileMapComponent;
    14.     protected Tilemap tileMapClone;
    15.     protected Vector2 tileMapPosition;
    16.     protected bool hasDone = false;
    17.  
    18.     // Start is called before the first frame update
    19.     void Start()
    20.     {
    21.         if(!hasDone)
    22.         {
    23.             tileMapComponent = tileMapGameobjectOrigin.GetComponent<Tilemap>();
    24.             tileMapClone = Instantiate(tileMapComponent);
    25.            
    26.             tileMapPosition = (Vector2)tileMapClone.transform.position + (Vector2.right * 41);
    27.             tileMapClone.transform.position = tileMapPosition;
    28.             hasDone = true;
    29.         }
    30.     }
    31. }
    32.  
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,507
  3. The_wARmAcH1n3

    The_wARmAcH1n3

    Joined:
    Aug 5, 2023
    Posts:
    26
    I wrote it here because it's a scripting problem, maybe coders won't look in the 2D subforum.
     
  4. The_wARmAcH1n3

    The_wARmAcH1n3

    Joined:
    Aug 5, 2023
    Posts:
    26
    I got it to work with this line:

    Code (CSharp):
    1. tileMapClone.transform.SetParent(grid.gameObject.transform);
     
  5. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,507
    Reparenting won't change what cloning the tilemap does so I suspect you forgot that you always need to have it using a Grid otherwise all the tiles appear in the same location because there's no layout. Try disabling the Grid to see that effect.

    Yeah, why would 2D devs ever look on the very active 2D forum. ;) Also, everything is technically scripting so that would mean no physics, audio, timeline (etc) sub-forums! Please use the dedicated forums.