Search Unity

Question New Button.clicked Callback

Discussion in 'Scripting' started by Capricornum, Sep 4, 2020.

  1. Capricornum

    Capricornum

    Joined:
    Feb 1, 2018
    Posts:
    22
    According to Unity's documentation he Button.OnClick callback is obsolete. I am supposed to use Button.clicked.
    In my Visual studio this doesn't appear as an option though. Does anyone know how to use Button.clicked?
     
  2. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,145
    Button.clicked is an Action delegate. All of the below examples show adding and removing functions from the delegate as this allows you to use multiple events. If you only care about a single event you can use an equals sign and each new one will override the previous.

    Attaching a function
    Code (csharp):
    1. void Start()
    2. {
    3.     mybutton.clicked += OnClick();
    4. }
    5.  
    6. void OnClick()
    7. {
    8.     // do stuff
    9. }
    Removing a function
    Code (csharp):
    1. void RemoveMe()
    2. {
    3.     mybutton.clicked -= OnClick();
    4. }
    Attaching an anonymous function
    Code (csharp):
    1. void Start()
    2. {
    3.     mybutton.clicked += () => { // do stuff };
    4. }
    Official reference entry

    https://docs.microsoft.com/en-us/dotnet/api/system.action
     
    Capricornum likes this.
  3. Capricornum

    Capricornum

    Joined:
    Feb 1, 2018
    Posts:
    22
    That is very helpful thanks.
    Visual Studio was still showing an error when writing myButton.clicked.
    I now discovered that I have to do this:
    using UnityEngine.UIElements

    This seems to be very new.
     
    Cyber-Dog likes this.
  4. Zyblade

    Zyblade

    Joined:
    Jul 1, 2014
    Posts:
    141
    In case someone is wondering. It didn't work for me until I removed the parenthesis after "+= OnClick". Maybe it helps someone.
     
    Kurt-Dekker likes this.
  5. Cyber-Dog

    Cyber-Dog

    Joined:
    Sep 12, 2018
    Posts:
    352
    When in doubt... Ctrl + dot :D