I am trying to place a button onto a canvas background using C# script. I want the button specific to the canvas (i.e., if I move the camera to look at another canvas, I do not want the button visible).
My C# script is below. I have attached it to an empty game object. When I run the game, the Heirarchy panel of Unity shows that the canvas and button are created OK, and that
the button is a child of the canvas. The canvas appears in game view at the right size (200 x 200).
But in game view, there is no button!
The button is definitely present ; clicking on its name the Heirarchy panel shows me a location and size in the scene view that are exactly as specified in my C# script. But nothing happens when I click the region in game view where the button is supposedly present.
Unity's Inspector panel shows that a "Button (Script)" has been attached to my button object, with Rect Transform parameters as specified in my C# code. I tried messing with the colors, but still no button. The "On Click()" window contains nothing except the message "List is Empty".
How do I make the button appear in game view?
How do I make the button work (i.e., generate the Console message "button pressed")?
using UnityEngine; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine.EventSystems; public class TestScript : MonoBehaviour { private GameObject myGO; private Vector2 buttonSize; private Vector3 buttonPosition; void Start () { // setup a canvas myGO = new GameObject (); Canvas myCanvas = myGO.GetComponent<Canvas> (); myCanvas.renderMode = RenderMode.WorldSpace; RectTransform parentRectTransform = myGO.GetComponent<RectTransform> (); parentRectTransform.sizeDelta = new Vector2 (200, 200); // set size of parent rectangle // create and place the button Vector2 buttonSize = new Vector2 (10, 10); Vector3 buttonPosition = new Vector3 (150, -70, 1); CreateButton (myGO.transform, buttonPosition, buttonSize); } // end Start() public void CreateButton(Transform panel ,Vector3 position, Vector2 size) { GameObject button = new GameObject(); button.name = "Button"; button.transform.parent = panel; button.AddComponent<RectTransform>(); button.AddComponent<Button>().onClick.AddListener (handleButton); button.transform.position = position; } void handleButton() { Debug.Log("Button pressed!"); } } // end class TestScript 