- Home /
Adding child to Canvas
I've tried to research this myself and there are tons of answers about -- none of which that work.
I have this code here:
GameObject newButton = Instantiate(buttonPrefab, new Vector3(0f,0f,0f), Quaternion.identity) as GameObject;
newButton.transform.SetParent(loadCanvas.transform, true);
That obviously takes a button prefab and assigns it to a canvas. I've literally tried every combination of .transform.parent and SetParent I could (as other answers suggest) and I can't for the life of me avoid the error:
NullReferenceException: Object reference not set to an instance of an object
I'm assuming that's referring to my loadCanvas Canvas object being null, but it's used elsewhere in the script without error and is assigned in the inspector. Immediately before that in the code the canvas is SetActive(false), but that is not the issue (I've tried enabling it so that it was always active and it didn't change the results).
As soon as I move the button under the loadCanvas object in the hierarchy it renders. What gives?
Answer by FreeTimeDev · Jan 03, 2015 at 01:38 AM
Solved:
//Cast it as a Button, not a game object
Button newButton = (Button)Instantiate(buttonPrefab);
//Use .SetParent(canvasName,false)
newButton.transform.SetParent(loadCanvas.transform,false);
Your answer
Follow this Question
Related Questions
UI elements are not getting affected by lighting 0 Answers
Strange UI Button hover offset when using Worldspace Canvas in VR 4 Answers
My UI buttons work fine in editor but when I exported the game on Android, only some of them works. 0 Answers
Simulate Button presses through code unity 4.6 GUI 4 Answers