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

Invoke (Function, 0f) only executed after other parts of function have finished, why and how to stop

Discussion in 'Editor & General Support' started by egg_citizen, May 28, 2019.

  1. egg_citizen

    egg_citizen

    Joined:
    Jan 3, 2019
    Posts:
    19
    Hello all,

    Another problem that occured with using Invoke.
    If I use the following code:
    Code (CSharp):
    1.         public void CodeExample()
    2.         {
    3.             CheckSkills("Chance");
    4.             Score();
    5.         }
    And CheckEmoSkills has the follwing code:

    Code (CSharp):
    1.  
    2. public string functionName = "FunctionICall";
    3. public int score = 0;
    4.  
    5. public void CheckSkills(string fieldname)
    6.         {
    7.             if (fieldname=="Chance")
    8.                     {
    9.                         Invoke(functionName, 0f);
    10.                     }
    11.         }
    12.  
    13.         public void FunctionICall()
    14.         {
    15.             score += 100;
    16.         }
    Then the code for Score() finishes before the Invoke(functionName, 0f) finishes.
    Score() is used to set the variable in different fields and Text.text values.
    Since the Score() function uses the same score-variable, this causes a misrepresentation of the actual score.
    How can I make sure the invoke finishes before the Score() is started?

    I couldn't get it to work with IEnumerator and StartCoroutine, as coroutine doesn't seem to work with the Invoke.
     
  2. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,613
    That's just how Invoke works. If you want to call a function and have that function be variable (I guess that's why you are using Invoke?) then you should probably use a delegate or a Unity event instead.
     
  3. egg_citizen

    egg_citizen

    Joined:
    Jan 3, 2019
    Posts:
    19
    I have found what I'm looking for.
    This part:
    Code (CSharp):
    1. public void CheckSkills(string fieldname)
    2.         {
    3.             if (fieldname=="Chance")
    4.                     {
    5.                         Invoke(functionName, 0f);
    6.                     }
    7.         }
    8.  
    became this part:
    Code (CSharp):
    1.  
    2.         public void CheckSkills(string fieldname)
    3.         {
    4.           if (fieldname=="Chance")
    5.                   {
    6.                       var mi = GetType().GetMethod(functionName);
    7.                       Action useSkill = (Action)mi.CreateDelegate(typeof(Action), this);
    8.                       useSkill();
    9.                   }
    10.         }
    11.