Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Callback from an event

Discussion in 'Scripting' started by AshyB, Jan 25, 2017.

  1. AshyB

    AshyB

    Joined:
    Aug 9, 2012
    Posts:
    191
    I assume this is the correct place to post this, just have a general C# question. Can you have an event do a callback?

    For example can we have this;

    Code (csharp):
    1.  
    2. void Start()
    3. {
    4.    FindSomething("this is the thing to find", () => { Debug.Log("This should be called last"); });
    5. }
    6.  
    7. void FindSomething(string value, System.Action OnComplete)
    8. {
    9.    SomeStaticClass.DoThisMethod(value).onComplete += (EventMethod) =>
    10.    {
    11.       Debug.Log("This should be called second");
    12.  
    13.       OnComplete();
    14.    }; // this makes the debug.log print "This should be called second" and then "This should be called last" but doesn't call the EventMethod() below at all.
    15. }
    16.  
    17. void EventMethod(string result, System.Action OnComplete)
    18. {
    19.    Debug.Log("This should be called first");
    20.  
    21.    // do something with the result string
    22.  
    23.    OnComplete();
    24. }
    25.  
    Now before you ask why can't I just do a callback with the DoThisMethod() like the others is because the SomeStaticClass belongs to another asset store product and I don't want to have to rewrite all their code for this to work.
     
  2. AshyB

    AshyB

    Joined:
    Aug 9, 2012
    Posts:
    191
    Think I figured it out, I can get rid of the EventMethod() all together and use the (EventMethod) which is now the returned string from the DoThisMethod().onComplete. So now I do this instead;

    Code (csharp):
    1.  
    2. void FindSomething(string value, System.Action OnComplete)
    3. {
    4.    SomeStaticClass.DoThisMethod(value).onComplete += (result) =>
    5.    {
    6.       // do something with result string
    7.  
    8.       OnComplete();
    9.    };
    10. }
    11.