3
votes

My scene has basic game objects (camera, canvas with two child image and button). enter image description here

I make a prefab of a button, now the prefab is on the project view, I want to instantiate this prefab button from within the script, and I want it to be drawn inside the canvas.

For that, I make a script file, attach it to the canvas as a script component. Here is my script implementation:

using UnityEngine;

public class QuizManager : MonoBehaviour {

    public Transform suggestionBtn;

    // Use this for initialization
    void Start () {
        Instantiate (suggestionBtn, new Vector3 (100, 400, 0), Quaternion.identity);
}


// Update is called once per frame
    void Update () {

    }
}

Of course, the suggestionBtn is the prefab, that's why I make a reference of it to the script variable (drag the prefab from the project view to the script component).

enter image description here

Now when I run the game, I noticed the clone of the prefab is added above all game objects in the hierarchy view (I am expecting to get it added inside the canvas):

enter image description here

And also it has wrong dimension (very very small, it is barely visible), here how it looks after I zoom it in

enter image description here

So my question is how can I instantiate the prefab correctly with its normal size and position it correctly relatively to the canvas (child of the canvas) ?

Thanks

2

2 Answers

5
votes

You can correctly initialize the transform (under correct game object hierarchy) by assigning the instance to a variable and then changing its parent.

public class QuizManager : MonoBehaviour {

    public Transform suggestionBtn;

    // Use this for initialization
    void Start () {
        Transform clone =  (Transform)Instantiate (suggestionBtn, 
                           new Vector3 (100, 400, 0), Quaternion.identity);

        // make instance the child of current object
        clone.parent = gameObject.transform; 

        // adjust the scale
        clone.transform.localScale = new Vector3(Xval, Yval, Zval);
    }

}

You can change the localScale from the assigned clone variable after instantiation.

0
votes

From your screenshot of the hierarchy view at runtime, your instantiated button is not nested under the Canvas, therefore it will not be rendered by the Canvas Renderer.

When you instantiate it, you need to set the transform.parent to the canvas gameobject's transform.

var newButton = Instantiate (suggestionBtn, new Vector3 (100, 400, 0), Quaternion.identity) as GameObject;
newButton.transform.parent = GameObject.Find("Canvas").transform;