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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

UI prefabs instantiated at runtime are flipped the wrong way

Discussion in 'UGUI & TextMesh Pro' started by ikefrc, Oct 13, 2015.

  1. ikefrc

    ikefrc

    Joined:
    Jul 3, 2012
    Posts:
    81
    I have a UI prefab which I need to instantiate at runtime, since I don't know when and how many I will need.

    The following picture shows it best, to the right is the prefab instantiated during runtime, to the left the same prefab is dropped into the Hierarchy manually. The right one is flipped the wrong way and creates those red crosses.



    The only way to fix the right one is to manually resize it into the negative to flip it.

    I presume thats because the GameObject is first instantiated and only then parented to the Canvas. Are there any workarounds that fix it?
     
  2. jcredible

    jcredible

    Joined:
    Dec 4, 2012
    Posts:
    24
    What call are using to set the parent? If it's "SetParent" on the transform then notice that the second (optional) value is whether the gameObject should keep the same world matrix. I believe it defaults to true. At least in my work, I've been setting it to false more often than not (for UI stuff).

    See: Transform.SetParent
     
  3. ikefrc

    ikefrc

    Joined:
    Jul 3, 2012
    Posts:
    81
    Yup that's what I'm currently doing (I've tried both - true is even worse)
    Code (csharp):
    1. floater.transform.SetParent(canvas, false);
    Still flipped the wrong way though
     
  4. Kylotan

    Kylotan

    Joined:
    Feb 17, 2011
    Posts:
    212
    I expect this is something to do with how the anchors are set, which can effectively flip something relative to its parent if the calculated values end up putting the right hand edge further left than the left-hand edge.

    What are the anchor values for the top level object in the prefab?
     
  5. ikefrc

    ikefrc

    Joined:
    Jul 3, 2012
    Posts:
    81
    You are most likely right, the anchors were set to center stretch. What I did to solve my problem was having the object already in world as a child of Canvas, but disabled. So whenever I need another one I just clone it with Instantiate and set it active which does the trick for me. That's actually more convenient since I can quickly change things on it. Also the anchor is set to middle center now.

    Hopefully this thread will help someone out in the future :)