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

Instantiate issue?

Discussion in 'Scripting' started by asarj, Dec 24, 2019.

  1. asarj

    asarj

    Joined:
    Dec 24, 2019
    Posts:
    2
    Sorry if this is a common problem, but I have some code that's trying to access the height of a text box (childed in a GameObject) right after instantiating it, and for some reason it's returning 0. I suspect this is because of something about instantiate() that I don't know, or because it's nested in a foreach(). It works fine for all of the boxes that haven't been instantiated this frame, but not the newest one. Thanks for the help! Here's a sample of the code:

    Where the object is instantiated:
    Code (CSharp):
    1.  
    2.     public void advance() {
    3.         TimeSinceAdvance = 0;
    4.         if (lines.Count > 0){
    5.             GameObject newBox = (Instantiate (CurrDialogTextPrefab, this.transform, false));
    6.             Text newBoxText = newBox.GetComponentInChildren<Text> ();
    7.             handledBoxes.Enqueue(newBox);
    8.             newBoxText.text = lines.Dequeue();
    9.             adjustHeights ();
    10.         }
    11.     }
    Where the height is accessed (in adjustheights()):
    Code (CSharp):
    1. ...
    2.  
    3.         float checkHeight = 0f;
    4.  
    5.         foreach (GameObject x in handledBoxes) {
    6.             checkHeight += x.GetComponentInChildren<RectTransform>().rect.height;
    7.             //ALWAYS RETURNS 0 FOR THE HEIGHT OF THE MOST RECENTLY INSTANTIATED BOX
    8. ...
    9.         }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,469
    Aha! I think I found your problem... check out this documentation:

    https://docs.unity3d.com/Manual/class-RectTransform.html

    Specifically under the Details section, there's a blurb about how some properties are not updated until end of frame.

    The good news is there appears to be a workaround where you force the canvas to update this frame.

    If that is really the problem you're experiencing, maybe that's the fix for you.

    As an aside, did you know the UI source is open? It's all available here:

    https://bitbucket.org/Unity-Technologies/ui/src/2019.1/

    Merry Unity3D Christmas and may all your yuletide RectTransforms be updated properly.
     
    asarj likes this.
  3. asarj

    asarj

    Joined:
    Dec 24, 2019
    Posts:
    2
    Fantastic! Thank you so much - it's a Merry Coding Christmas after all! I had to insert ForceUpdateCanvases() after the instantiate line instead of in a Start(), but once I made that little change it worked like a charm. Thank you again!!!!

     
    Kurt-Dekker likes this.