- Home /
Instantiating UI elements in 4.6
Hey all!
I seem to be having an issue with button position and scale when I programmatically instantiate buttons on my menu. I'm getting a list of servers and then instantiating a button for each server. However when I child the button to it's parent container after instantiating it the button disapears into a thing red line as shown below.
Here's the code that instantiates and places that button.
foreach (HostData host in hostData) {
//Canvas.Instantiate(metaButton);
Button button = Instantiate(metaButton, new Vector2(s_buttonFather.position.x, s_buttonFather.position.y + buttonOffset), Quaternion.Euler(Vector3.zero)) as Button;
// button.transform.SetParent(GameObject.Find("Canvas").transform, false);
button.transform.SetParent(s_buttonFather.transform, true);
button.GetComponent<ServerButton>().hostData = host;
button.SendMessage("setName");
buttonOffset += button.image.sprite.bounds.size.y + .7f;
}
If I change the code above to not relocate the child object when I set the parent then the object is displayed out of the display view of the canvas camera as shown below. What's up with this? Am I making some glaring error that I am just somehow missing? Thanks so much!
Answer by malkere · Apr 23, 2015 at 10:55 AM
This was driving me nuts, but the manual says:
"When setting the parent of the instantiated UI element, it’s recommended to do it using the Transform.SetParent method with the worldPositionStays parameter set to false."
this one setting fixed all my problems.
Answer by BOT_Sam. · Jan 26, 2015 at 11:17 AM
http://docs.unity3d.com/Manual/HOWTO-UICreateFromScripting.html
^^ Hope this helps ^^