Search Unity

Problem with instantiate UI prefabs

Discussion in 'UGUI & TextMesh Pro' started by Stream, Sep 29, 2014.

  1. Stream

    Stream

    Joined:
    Oct 28, 2013
    Posts:
    37
    When I instantiate prefab with RectTransform on it in most cases it works wrong. Usually ancoredPosition and deltaSize resets and I have to set it again from script. There are another bug that I think linked to the same. I use ReferenceResolution that in all phones interface scale and looks well. And it works well with UI elements that allready exist on scene, but when I instantiate prefab with RectTransform its not scale at all. This bug has always is reproduce (((
     
  2. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    557
    Are you making sure to set the instance's parent to the Canvas (or a Canvas element) using transform.SetParent(parent, false)?
     
  3. TimBur

    TimBur

    Joined:
    Jan 17, 2013
    Posts:
    35
    I also struggled with that instantiation issue. It's not so much 'right' or 'wrong', it's just what the system does. When you use the simple version of Instantiate, the one without the position or rotation argument, then the new object just shows up at some semi-random place. I believe this is what is supposed to happen.

    To instantiate an object at a specific position / rotation, you have two options:

    1) Do what you've been doing, use the simple version of Instantiate, and then use anchoredPosition and localPosition to relocate the new object.

    2) Use the longer call to Instantiate, the one that has both a position and a rotation argument. For example, if you want the new object to have the same position and rotation as the prefab, you do this:

    Code (CSharp):
    1.  
    2. newobject = Instantiate (prefabobject, prefabobject.transform.position, prefabobject.transform.rotation) as GameObject;
    3.  
     
    hamidaminirad5 and ayhaab-pasha like this.
  4. Stream

    Stream

    Joined:
    Oct 28, 2013
    Posts:
    37
    I do this:
    LeaderboardSlot leaderboardSlot = Instantiate(leaderboardSlotPrefab) as LeaderboardSlot;
    leaderboardSlot.transform.parent = leaderbordGrid;
     
  5. Stream

    Stream

    Joined:
    Oct 28, 2013
    Posts:
    37
    The problem isn't in "what place the object appears". Example: I have prefab, It's Image this 10,10,0 position. It have children Text this 50,0,0 local position. When I instantiate prefab Text now have 0,0,0 local position.
    Another part of the problem is that the object appears in the wrong scale (it is smaller / bigger than it should be). Its scale should establish ReferenceResolution, but he don't for some reason
     
  6. amit1532

    amit1532

    Joined:
    Jul 19, 2010
    Posts:
    305
    Have this problem too.. I didnt see any information on how to instantiate correctly the new UI... only how to position them staticly before the game starts..

    If i have a canvas and i want to instantiate any ui to it, and the resolution doesnt stay the same as when I created the prefab of the UI, it will be positioned wrong when I instantiate it in the new resolution...
    Also, when using ReferenceResolution the instantiated UI wont have the right size as it should have if the UI wouldnt be instantiated (but will be there staticly)
     
  7. Stream

    Stream

    Joined:
    Oct 28, 2013
    Posts:
    37
    Great news and many thanks to Senshi!

    I have tried using "transform.SetParent(anotherTransform, false)" instead of "transform.parent = anotherTransform" and it works perfectly now!
     
  8. slumtrimpet

    slumtrimpet

    Joined:
    Mar 18, 2014
    Posts:
    372
    Hit this same issue and just to chime in...

    Doesn't scale prefab to UI scale:
    go.transform.parent = this.rows.transform;

    Doesn't scale prefab to UI scale:
    go.transform.SetParent(this.rows.transform);

    DOES scale prefab to UI scale :):
    go.transform.SetParent(this.rows.transform, false);
     
    Last edited: Jul 19, 2015
  9. Sposito

    Sposito

    Joined:
    May 4, 2014
    Posts:
    16
    With me is even weirder, the instances appears in the editor but they are no visible, as the would appear if they were not child of canvas, what isn't the case! any idea what is going on here?
     
    nathanjams and firejerm like this.
  10. Keseren

    Keseren

    Joined:
    May 8, 2015
    Posts:
    3
    Thanks so much for that! Was searching around for a bit, almost 0 info of how to solve these things. The 3rd option worked for me :)
     
    Hecolo likes this.
  11. pedrevans

    pedrevans

    Joined:
    May 8, 2013
    Posts:
    10
    This fixed my problem too. I couldn't understand why there were such huge gaps between the items in a vertical Iayout group. I spent several hours researching this. The breakthrough came after creating manually instances of my prefab before letting the code do it and then comparing the inspector output. Now instead of googling for big gaps I was googling for wrongly sized prefab instantiations and so stumbled over this page. Thank you, Senshi, you saved me yet more hours of pain.
     
    ivan_p and Senshi like this.
  12. David-Kamunyu

    David-Kamunyu

    Joined:
    Jul 23, 2012
    Posts:
    23
    That did it for me. Thanks!
     
    Senshi likes this.
  13. cwperkins83

    cwperkins83

    Joined:
    Jul 19, 2012
    Posts:
    1
    Had to chime in on my personal problem and fix. I had a problem with the Instantiated UI Button being way too big. It does NOT follow the scale of it's parent. My background panel was at 0.73 scale and the instantiated button was at 1.0. Don't scale your UI's, readjust their widths and heights.
     
  14. TurretLemur

    TurretLemur

    Joined:
    Mar 25, 2015
    Posts:
    1
    So I'm always makin simple mistakes... here's what I finally realized when none of these worked..... my prefab texts were children of another canvas in my project folder.... when it was reading the transform for instantiation, it was pickin up the 0,0,0 even though I had put texts all over the place...(that's what I'm guessin...) Since I had my stuff right where I wanted it (and de-parenting messed up the positions, and readjusting those was gonna take a while) I instantiated at the prefab's transform.localPosition instead of position and they all came out great...
     
    pKallv likes this.
  15. codegasm

    codegasm

    Joined:
    May 3, 2015
    Posts:
    38
    Thanks for posting this! The last variant both solved a similar problem I was having and gave me deeper insight into how Unity works. The reason that it works and the explanation to why I keep running into strange scaling and positioning issues when instantiating prefabs is in the docs:
     
  16. breban1

    breban1

    Joined:
    Jun 7, 2016
    Posts:
    194
    Thumbs up Senshi, that did it for me! I was putting true, but I needed false.

    transform.SetParent(parent, false)
     
    radiantboy likes this.
  17. ColorStorm

    ColorStorm

    Joined:
    Jul 4, 2012
    Posts:
    28
    Thanks Senshi!
    i scratched my head for a while with this issue. It does make sense, but first i didn't think the issue was in the parenting, i thought it was in some canvas component paramenter.
     
  18. Mentoliptus

    Mentoliptus

    Joined:
    Oct 14, 2014
    Posts:
    2
    Thank you Senshi!
    Passing the second parameter as false solved a similar problem I had! Now the children I instantiate a run-time scale with the parent that is added in the editor.
     
  19. v_osnovnom_bezvreden

    v_osnovnom_bezvreden

    Joined:
    Jan 9, 2017
    Posts:
    7
    Thank you, that helped!
     
  20. Rebaken-Enterprises

    Rebaken-Enterprises

    Joined:
    Nov 17, 2014
    Posts:
    17
    I was using SetParent, just not the false setting ... sigh. Fixed everything. Thanks!
     
  21. ShantekDev

    ShantekDev

    Joined:
    Aug 20, 2015
    Posts:
    26
    My HERO! I've been pulling my hair out for days following the Shop UI tutorial using their exact code and my buttons being blown out massively. And having false in the set parent fixed it so thanks so much!
     
    Zefiren likes this.
  22. JuanAmaral

    JuanAmaral

    Joined:
    Nov 24, 2016
    Posts:
    1

    THANKS BRO
     
  23. pKallv

    pKallv

    Joined:
    Mar 2, 2014
    Posts:
    1,190
    THANKS this solved my problem.
     
  24. jdelange

    jdelange

    Joined:
    Mar 6, 2016
    Posts:
    2
    Brilliant! This has put an end to days of debugging!!!
     
    radiantboy and Senshi like this.
  25. JVC1000

    JVC1000

    Joined:
    Jul 2, 2017
    Posts:
    1
    Thanks Senshi, frustration is over!
     
    Senshi likes this.
  26. AlexS64

    AlexS64

    Joined:
    Oct 5, 2017
    Posts:
    1

    You are a god. Thank you!
     
    Senshi likes this.
  27. Lamer80

    Lamer80

    Joined:
    Apr 1, 2017
    Posts:
    2
    I had to re-set it's position e.g.
    Code (csharp):
    1.  
    2.             GameObject g = (GameObject)Instantiate(gameObject, transform.position, Quaternion.identity);
    3.             g.transform.SetParent(transform.parent, false);
    4.             g.transform.position = transform.position;
    5.  
     
  28. The_Craeb

    The_Craeb

    Joined:
    Aug 3, 2017
    Posts:
    2
    I've been banging my head against this for a while, too with slightly different circumstances. I have a scroll list which populates with profile names from a list of names that can be any length. I was getting all kinds of crazy sizes for my buttons, depending on the resolution at the time. The buttons were also very clearly stretched and the text, when it was the right size, was pixelated and blurry.

    The code I wound up with which worked was

    Code (CSharp):
    1. GameObject spawnedGameObject = (GameObject)GameObject.Instantiate(panelPrefab);
    2.             spawnedGameObject.transform.SetParent(contentPanel);
    3.             spawnedGameObject.transform.localScale = new Vector3(1, 1, 1);
    The key here was the last line to set the local scale. Once that was applied, the prefabs scaled up and filled up the space properly.
     
    Ctanner1 likes this.
  29. FlightOfOne

    FlightOfOne

    Joined:
    Aug 1, 2014
    Posts:
    668
    Below has been the most reliable way for me to position and stretch
    Code (CSharp):
    1.             _uiInvPanel.transform.SetParent(_playerInventoryHolder.transform);
    2.             _uiInvPanel.RectTransform.sizeDelta = _playerInventoryHolder.rect.size;
    3.             _uiInvPanel.RectTransform.anchoredPosition = _playerInventoryHolder.anchoredPosition;
     
  30. Mathijs_Bakker

    Mathijs_Bakker

    Joined:
    Apr 28, 2014
    Posts:
    25
    I had the same in my UI scroll list. Instantiating a prefab game object - with SetParent and it's parameter: worldPositionStays set to false - was working fine.

    However when I returned it to the object pool and activate it again from the pool... the damn thing shrank every time more and more. Making sure to set the transform localScale to 1 to prevent scaling madness.

    Code (CSharp):
    1. GameObject menuItem = _menuItemPool.GetObject();
    2. menuItem.transform.SetParent(GetComponent<Transform>(), false);
    3. menuItem.transform.localScale = new Vector3(1, 1, 1);
     
    Ctanner1 and Advancensar like this.
  31. ematsuno

    ematsuno

    Joined:
    Oct 13, 2015
    Posts:
    27
    Workaround retains the prefab values only after activating it through code if it's instantiated inactive.

    Algorithm:

    1) Instantiate the prefab inactive
    2) Set the object active.

    Code:

    public class SomeClass: MonoBehaviour {

    public GameObject Prefab;

    RetainPrefabParms()
    {
    Prefab.SetActive(false);
    GameObject buttonMask = Instantiate(Prefab);
    buttonMask.transform.SetParent(this.transform,false);
    buttonMask.SetActive(true);
    }
     
    jk-linuon and prakyath_unity like this.
  32. ayhaab-pasha

    ayhaab-pasha

    Joined:
    Dec 6, 2015
    Posts:
    5
    Thanks a lot for this. This is what i had to do. Im trying to add health bar on game objects on run time. I made a prefab and everything for the Health bar. But it wasn't appearing over the gameobject. I did this and the health bars were shown above the game objects.
     
  33. Ryan900

    Ryan900

    Joined:
    Jun 7, 2019
    Posts:
    4
    This worked perfectly, thanks!
     
  34. murp35

    murp35

    Joined:
    Nov 22, 2019
    Posts:
    2
    Thank you. This has been stressing me for a while
     
    Senshi likes this.
  35. YoungJoonLilBro

    YoungJoonLilBro

    Joined:
    Sep 27, 2021
    Posts:
    2
    It works for me, thanks!
    I used
    [gameObject.transform.parent = mother.transform; ] : It doesn't work :(
    and [gameObject.transform.SetParent(mother.transform,false); ] : It works! ;)
     
  36. radiantboy

    radiantboy

    Joined:
    Nov 21, 2012
    Posts:
    1,633
    man I didnt know that, saved my day thanks!!
     
    Senshi likes this.
  37. brian-nielsen

    brian-nielsen

    Joined:
    Apr 18, 2018
    Posts:
    15
    All the way into 2022 you are still saving devs. Bless you.

    My specific issue had to do with instantiating UI elements at runtime for a dynamic menu.
     
    Senshi and Neil-Corre like this.