Search Unity

Duplicate elements inside the canvas

Discussion in 'UGUI & TextMesh Pro' started by Maklaud, Jan 14, 2019.

  1. Maklaud

    Maklaud

    Joined:
    Apr 2, 2013
    Posts:
    551
    Hi All,

    I'm making some game elements inside canvas. It whould be a map with map parts. One map part is a prefab, but maybe it doesn't matter, becase I add one copy to the canvas at start. Then I duplicate this first copy using this code:
    Code (CSharp):
    1.  
    2. var rectTransform = FirstMapPart.GetComponent<RectTransform>();
    3.  
    4. for (var i = 0; i < 5; i++)
    5. {
    6.             var mapPart = Instantiate(FirstMapPart, rectTransform.position, rectTransform.rotation);
    7.             mapPart.transform.SetParent(MapGameObject.transform);
    8. }
    Where FirstMapPart is the first part whicl should be duplicated. After this code is executed, I have all the necessary duplicated items, it's correct: 1.png

    This is the initial map part, it's also correct: 2.png

    And this is the copied part, it's Scale is wrong: 3.png

    What did I do wrong? I tried to get RectTransform component and change its localScale, but it didn't help.

    Thank you!
     

    Attached Files:

    • 1.png
      1.png
      File size:
      3.5 KB
      Views:
      718
    • 2.png
      2.png
      File size:
      16.3 KB
      Views:
      723
    • 3.png
      3.png
      File size:
      15.3 KB
      Views:
      667
  2. Hosnkobf

    Hosnkobf

    Joined:
    Aug 23, 2016
    Posts:
    1,096
    When you instanciate this way your object is put in the root of the scene. then it is moved into a canvas. The canvas uses a very special transformation logic (that's why all the UI stuff use RectTransform rather than Transform) and that is why the transformation is messed up then.

    either pass false as second parameter to SetParent OR use the overload of instanciate where you can specify the parent directly and remove the SetParent call (better approach):
    Code (CSharp):
    1. var mapPart = Instantiate(FirstMapPart, rectTransform);
     
  3. Maklaud

    Maklaud

    Joined:
    Apr 2, 2013
    Posts:
    551
    Hosnkobf, thanks for your reply!
    I've just found the solution by changing localScale AFTER setting the parent and it helped.
    But I think that passing false to SetParent is a better choise. Thanks!
     
  4. Hosnkobf

    Hosnkobf

    Joined:
    Aug 23, 2016
    Posts:
    1,096
    And even better (as I already wrote) is to pass the parent directly into the instantiate method.
     
  5. Maklaud

    Maklaud

    Joined:
    Apr 2, 2013
    Posts:
    551
    Yes, really better. I compared other properties, the second way copies them correctly. Thanks again!