Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

[Solved] Button Prefab onclick not working

Discussion in '2018.3 Beta' started by Arnuga, Oct 3, 2018.

  1. Arnuga


    Nov 10, 2016
    I'm not sure if this is related to the beta or not. I have tried to add onclick events in multiple ways to a button and none work.

    Attempt 1:
    Create prefab which is a panel of size 100x100 which contains a button centered inside it of size 80x80.
    The button inside this prefab has an attached script (ButtonScript) which has a public void Foo() method that simply does a Debug.Log("foo").

    The button inside the prefab has an onclick that is set to editor and runtime, the "object" is the button itself and the method is selected via the dropdown in the onclick inspector area as ButtonScript.Foo

    This prefab is loaded via an Instantiate(name_of_prefab) call. When I run my scene the button is visible but when I click it with a mouse, nothing happens, no debug log, no visual change, nothing. The button prefab has a "Button (Script)" component that was auto created when I created the button element, this has a checkbox for Interactable which is clicked on and the transition is set to simple (I didn't change any of these defaults).

    Attempt 2:

    Same prefab, remove the onclick in the inspector. Change the buttonScript that is attached to the button to have a void Start() function.
    This script has the following code:

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    4. public class ButtonScript : MonoBehaviour
    5. {
    6.     void Start()
    7.     {
    8.         Button button = this.GetComponent<Button>();
    9.         button.onClick.AddListener(Foo);
    11.     }
    13.     public void Foo()
    14.     {
    15.         Debug.Log("foo");
    16.     }
    17. }
    This also seems to do nothing, break points don't ever trigger on the Foo method. I have also tried this as an Awake() function, I have tried the addListener as a lambda and as a delegate. Nothing.

    Any help would be greatly appreciated!
    laserbahia likes this.
  2. Carpe-Denius


    May 17, 2013
    Can you see the button change color when you hover or click? If not, see if you have an event system in your scene.
  3. Arnuga


    Nov 10, 2016
    I do but the buttons don't visually appear to be clicked. I deleted and recreated by button prefabs from scratch and now they work. Thank you for taking the time time read by plea.