C# - Creating Canvas UI button on click in code
Hello world!
I'm having a problem creating an on click using C# on a canvas UI button. I don't want to make my on click in the editor because I need more control so i'm making it in code. The script below is attached to the canvas ui button.
I think the problem is coming from the way i'm trying to grab a script from a different game object? Any suggestions on how I can fix this?
Errors i'm getting:
Assets/OnClick_Button_Canvas.cs(13,9): error CS0246: The type or namespace name
TQGGameController' could not be > found. Are you missing a using > directive or an assembly reference? > Assets/OnClick_Button_Canvas.cs(20,9): > error CS0103: The name >
TQGGameController' does not exist in the current context
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using System.Collections;
public class OnClick_Button_Canvas : MonoBehaviour
{
public Button buttonPrefab; //default button
void start()
{
GameObject go = GameObject.Find("GameController");
TQGGameController.ChooseAnswer other = (TQGGameController.ChooseAnswer)go.GetComponent(typeof(TQGGameController.ChooseAnswer));
buttonPrefab.onClick.AddListener(delegate { MyMethod(); });
}
void MyMethod()
{
Debug.Log("Button Clicked");
TQGGameController.ChooseAnswer();
}
}
Answer by UsmanAbbasi · May 08, 2016 at 05:54 AM
Use "using" directive to include the namespace in which "TQGGameController" is available. If you were able to use "TQGGameController" in some other script then compare all the "using" directives in that script with this one to find the proper namespace to include in this script.