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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Can't catch a button's On Click event

Discussion in 'Getting Started' started by Cool_P, Oct 28, 2015.

  1. Cool_P

    Cool_P

    Joined:
    Oct 28, 2015
    Posts:
    2
    I'm a newbie and have completed the roller ball project and added some extras - so far so good. Experimenting with the UI but cannot get a button to call my function when clicked. To remove any distractions have created a new project, added a button, a script that writes to the console log and then called the script from the On Click. The button changes colour when clicked but does not call my script. Help! Two screen shots attached showing what I've done.
     

    Attached Files:

  2. Schneider21

    Schneider21

    Joined:
    Feb 6, 2014
    Posts:
    3,510
    It looks like what you've done is drag your script to the On Click assignment box, when what you actually should be doing is dragging a Game Object from the scene there. That Game Object would have your clickButton script attached to it. Then, from the dropdown, you'll be able to select clickButton.PressMe, which will run the function you've written.

    It's a bit confusing at first, but when you get the hang of it, it gives you a lot of flexibility to add functionality without having to write functions, even. For example, if I wanted a button to make an object disappear, I just drag that object to the button's On Click, and call the GameObject.SetActive(false) function.

    For custom functions, I've been creating a script called GUIEvents and attaching it to the EventSystem object that gets created automatically when you add a Canvas. I then assign that to buttons that need to do things not handled by other objects in the scene (like loading the Main Menu scene or something).
     
    Ryiah likes this.
  3. Cool_P

    Cool_P

    Joined:
    Oct 28, 2015
    Posts:
    2
    Thanks Schneider21, that works as you said. The flexibility of linking scripts through objects is something I will watch out for.