- Home /
uGUI UI Button onclick static methods
Is it possible for uGUI buttons to access onclick methods that are static? It seems like only instances do not show up as "missing"
Answer by Kiwasi · Nov 26, 2014 at 07:06 AM
Currently no. You have to use an instance method as a wrapper to call the static method.
There are some complex technical reasons. Events are called on instances, not on the class itself. Yeah, I'm not really sure of the exact reasons, just that it currently is not supported.
Wrapper methods are pretty easy.
public class $$anonymous$$yClass : $$anonymous$$onoBehaviour {
public static void $$anonymous$$yStatic$$anonymous$$ethod(){
Debug.Log("I just called a static method from a button");
}
public void $$anonymous$$yStaticWrapper (){
$$anonymous$$yStatic$$anonymous$$ethod();
}
}
Seems rather extraneous or redundant to have yet another instance wrapper for each static method..
Don't complain to me. Send feedback to Unity. :)
You also have to use the wrapper method for calling non monobehaviour methods. Its all still much more efficient then the old OnGUI system.
Answer by Untherow · Jun 07, 2018 at 10:39 PM
I found a work around to this that kind of simulates static methods:
Add your script onto a gameobject and make it a prefab. Now you can select the prefab in your button onclick and it will work just fine but you still need to use non static methods.
I really don't understand though why, even today, those static functions are not supported. Would seem like a no-brainer to me.
Answer by Moeyvozhenie · Sep 22, 2017 at 08:14 PM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
public class BtnForStatic : MonoBehaviour {
private Button btn;
// Use this for initialization
void Start () {
btn = GetComponent<Button>();
}
public void AddBtnListener(UnityAction call)
{
btn.onClick.AddListener(call);
}
}
Your answer
Follow this Question
Related Questions
uGUI Button without renderer 3 Answers
Adding functions in editor 1 Answer
UI Button and Color Tint Transition issue 0 Answers