Can someone give me an example of programmatically (not using a prefab) creating a button in Unity 5 using C# that has the following features?
My attempt was:
main.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class main : MonoBehaviour {
public Canvas c;
// Use this for initialization
void Start () {
createButton ("minion",999);
}
// Update is called once per frame
void Update () {
}
//this is giving a button prefab all the methods from the class btnController
void createButton(string name,int val){
GameObject go =new GameObject();
go.AddComponent<btnController>();
go.transform.SetParent (c.transform,false); //add the gameobject to the canvas
go.AddComponent<Button> ();
//Button btnChild = go.GetComponent<Button> ();
//btnChild.GetComponent<Text>().text = "hello";//doesnt work
//go.GetComponentInChildren<Text>().text = "hello!";
btnController bc= go.GetComponent<btnController>(); //get reference to script for this button prefab
bc.Setup(name,val);//set values in this script for the GameObject to hold
GameObject inst =Instantiate (go);
}
}
btnController.cs
using UnityEngine;
using System.Collections;
public class btnController : MonoBehaviour {
string name="test";
int value=6;
//this script is attached to the button prefab. the onClick of the button prefab points to this OnClick method
public void Setup(string n, int v){
this.name = n;
this.value = v;
//Debug.Log ("in button setup:"+name+" "+value.ToString());
}
//OnClick is public so I can set the On Click () function to this method (in the prefab button)
public void OnClick(){
Debug.Log("btn clicked: "+this.name+" "+this.value.ToString());
}
}