Instantiate issue?

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:

    public void advance() {
        TimeSinceAdvance = 0;
        if (lines.Count > 0){
            GameObject newBox = (Instantiate (CurrDialogTextPrefab, this.transform, false));
            Text newBoxText = newBox.GetComponentInChildren<Text> ();
            handledBoxes.Enqueue(newBox);
            newBoxText.text = lines.Dequeue();
            adjustHeights ();
        }
    }

Where the height is accessed (in adjustheights()):

...

        float checkHeight = 0f;

        foreach (GameObject x in handledBoxes) {
            checkHeight += x.GetComponentInChildren<RectTransform>().rect.height;
            //ALWAYS RETURNS 0 FOR THE HEIGHT OF THE MOST RECENTLY INSTANTIATED BOX
...
        }

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.

1 Like

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!!!

1 Like