Problem with creating button via script.

// Sorry, I posted to the wrong room.

I have a code that take canvas and button prefab but after I run the code,

  1. The button is not inside the canvas I instantiated.

  2. I don’t see any button being instantiated in my game scene (but there is one in hierarchy )

    public GameObject buttonPrefab;
    public GameObject canvasPrefab;

     // Use this for initialization
     void Start () {
    
     	Canvas canvas = Instantiate (canvasPrefab, Vector3.zero, Quaternion.identity) as Canvas;
     	Button button = Instantiate (buttonPrefab, Vector3.zero, Quaternion.identity) as Button;
     	button.transform.SetParent (canvas.transform,false);
    
     }
    

Thank you very much.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Test: MonoBehaviour {

	public GameObject canvasPrefab;
	public GameObject buttonPrefab;


	// Use this for initialization
	void Start () {


	    GameObject button = Instantiate (buttonPrefab, Vector3.zero, Quaternion.identity) as GameObject;
		GameObject canvas = Instantiate (canvasPrefab, Vector3.zero, Quaternion.identity) as GameObject;

		button.GetComponent<RectTransform>().SetParent (canvas.GetComponent<RectTransform>());

	}
}

@jade1209 You are Instantiate the gameobject as Button and Canvas. You will get Null Reference exception. Just Instantiate as GameObject like I post the code then use these GameObjects by getting their components.