Home > Software engineering >  How to get Prefab size before Instantiating?
How to get Prefab size before Instantiating?

Time:03-24

I have a Prefab made of an Image element and a Text element in the Image. Depending on the length of the text, the prefab gets wider or taller. In script, I need to change the text and get the new size (height, width) of the prefab BEFORE using Instantiate(prefab). My problem is that I'm always getting a size of 0, or the size of the original prefab, without the text modification. My script looks like that :

prefab.GetComponent<Text>().text = myNewText; //insert a long text, supposed to make the prefab wider
float newSize = prefab.GetComponent<Image>().preferredWidth // always getting 0 or the original width of the prefab

// do some things with newSize

Instantiate(prefab);

PS : There is no Collider or mesh renderer in my prefab.

I also tried .GetComponent<RectTransform>().sizeDelta or .GetComponent<RectTransform>().rect.size.y but I always get 0 or the size of the original prefab, without the longer text.

CodePudding user response:

My solution to this would be: Instantiate the prefab, Set it as inactive in the scene, get the size, modify it as you like, then set it active again. It should look something like this

Gameobject newPrefab = Instantiate(prefab);
newPrefab.SetActive(false);
float newSize = newPrefab.GetComponent<Image>().preferredWidth;
DoStuff();
newPrefab.SetActive(true);

Have not tested this, but I think this is why you are not getting a width before instantiating

CodePudding user response:

Figured it out thanks to helpers. If it can be useful to someone, here is what I changed :

Instantiate(prefab); 
prefab.GetComponent<Text>().text = myNewText; //edit some properties
prefab.SetActive(false); // set inactive in the same frame so that we can't see it
StartCoroutine(foo()); //start this coroutine with a WaitForEndOfFrame() and then I can get updated properties
prefab.SetActive(true); 
  • Related