Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Unity UI how to make instantiated gameobject to have rectTransform of the canvas/parent?

Discussion in 'UGUI & TextMesh Pro' started by zergrage, May 23, 2017.

  1. zergrage

    zergrage

    Joined:
    May 19, 2017
    Posts:
    3
    Code (CSharp):
    1. public GameObject canvas;  // the canvas
    2. public Gameobject changerPopup;  // UI prefab
    3.  
    4. GameObject changerSign = Instantiate(changerPopup, new Vector3(235, 350, 0), this.transform.rotation);
    5. changerSign.transform.SetParent(canvas.transform);
    6.  
    7.  
    this will make a UI at the screen. while it does make the object as wanted, the rect transform won't get fixed(?) to the newly set parent(the Canvas), but instead to where it was first made. how could I get it under canvas's rect transform? could be some too basic question, but couldn't find any answer anywhere so far :(

    I tried that, also tried

    GameObject changerSign = Instantiate(changerPopup, new Vector3(235, 350, 0), this.transform.rotation, canvas.transform);

    but still don't gets under canvas rect transform.

    struggling with this for 8 hours with no luck.. anyone know how to solve this mess, well I'll really be grateful :(

    using unity 5.5.1
     
  2. Dreams

    Dreams

    Joined:
    Sep 9, 2011
    Posts:
    22
    Is this what you're looking for?
    public static Object Instantiate(Object original, Transform parent, bool instantiateInWorldSpace);

    GameObject changerSign = Instantiate(changerPopup, canvas.transform, false);

    This will spawn the prefab and instantly make it a child of the canvas, while not keeping the worldspace position.
     
  3. SimonDarksideJ

    SimonDarksideJ

    Joined:
    Jul 3, 2012
    Posts:
    1,688
    You will also have to set the anchors manually if you want it to appear how you actually want it.
     
  4. zergrage

    zergrage

    Joined:
    May 19, 2017
    Posts:
    3
    yeah a bit late reply, turned out I needed to use localposition.

    ugh it was horrible to know this after all the struggles. thank you everyone for checking out to help anyway.