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. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Subscribing to a function/method

Discussion in 'Scripting' started by renman3000, Mar 16, 2018.

  1. renman3000

    renman3000

    Joined:
    Nov 7, 2011
    Posts:
    6,680
    Hi there,
    I was under the impression I could subscribe to a function on another object script like this....

    Code (csharp):
    1.  
    2. //object a
    3. public void do(){}
    4.  
    5.  
    6. //object b
    7. objectA.do += do;
    8.  
    9.  
    But I don't seem to be able to. Any ideas?

    Thanks
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,738
    You're looking for events and delegates.
    Code (csharp):
    1. // defines the "pattern" of the event
    2. public delegate void SomeCallbackFunction(string parameterTheFunctionExpects);
    3. // the event itself
    4. public event SomeCallbackFunction myCallback;
    5.  
    6. //call the event (always null check it)
    7. if (myCallback != null) {
    8. myCallback("Foo");
    9. }
    10.  
    11.  
    12. //subscribe to the event
    13. objectA.myCallback += myFunc;
    14. void myFunc(string myParam) {
    15. Debug.Log(myParam);
    16. }
    17.  
     
    renman3000 likes this.
  3. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,383
    Code (csharp):
    1. //object a
    2. public Action SomethingHappened;
    3. public void do()
    4. {
    5.     if (SomethingHappened != null) SomethingHappened();
    6. }
    7.  
    8. //object b
    9. void Start()
    10. {
    11.     objectA.SomethingHappened += DoWhenTriggered;
    12. }
    13.  
    14. public void DoWhenTriggered()
    15. {
    16.  
    17. }
     
    renman3000 likes this.
  4. renman3000

    renman3000

    Joined:
    Nov 7, 2011
    Posts:
    6,680
    Sweet!