Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only.

    Please, do not make any changes to your username or email addresses at id.unity.com during this transition time.

    It's still possible to reply to existing private message conversations during the migration, but any new replies you post will be missing after the main migration is complete. We'll do our best to migrate these messages in a follow-up step.

    On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live.


    Read our full announcement for more information and let us know if you have any questions.

Invoke with parameters?

Discussion in 'Scripting' started by NeophyteGamer, Sep 20, 2013.

  1. NeophyteGamer

    NeophyteGamer

    Joined:
    Aug 26, 2013
    Posts:
    38
    Possible stupid question but I couldn't find an answer. Can someone help me?

    Is it possible to invoke a function while passing parameters?

    like:

    Invoke("mymethodname", parameter1, parameter2, invoketime);

    function mymethodname(parm1,parm2)
    {
    etc...
    }

    Thanks in advance.
     
  2. BlackMantis

    BlackMantis

    Joined:
    Feb 7, 2010
    Posts:
    1,475
    I'm pretty sure no. If you only need to call it once why not use the norm.

    FunctionName(i : index, r : String) { }
     
    honor0102 and blox5000 like this.
  3. Tanel

    Tanel

    Joined:
    Aug 31, 2011
    Posts:
    508
    Nope, but you can use a coroutine.

    Code (csharp):
    1.  
    2. //In Start() or wherever
    3. StartCoroutine(Foo(p1,p2));
    4.  
    5. function Foo(param1,param2)
    6. {
    7. yield WaitForSeconds(timer);
    8. //Do stuff
    9. }
    10.  
    This is kind of pseudocodey, cause I've not used JS for a long time.
     
  4. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    You could probably get around it by passing an array.
     
  5. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    No, since you can't pass any parameters to Invoke. As mentioned above, use something else instead, like a coroutine.

    --Eric
     
  6. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    It takes a float parameter. Generally there's no distinction between that and an array, so it could take more than one float, unless it didn't work. It depends how low level the array is. If it sees an object, then it probably wouldn't work.
     
    Last edited: Sep 20, 2013
  7. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    What? 0_0
     
    Goreduc, Mashimaro7, Rukas90 and 3 others like this.
  8. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    The float is used for the time that the function will be invoked. It's not a parameter that's passed to the function.

    Er...no. If the parameter type is a float, then you can never use anything else for that parameter aside from a float. A few types will implicitly convert to a float (like an int), but the parameter will still be a float in the end after being converted, and can certainly never be any type of array.

    --Eric
     
  9. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    In c, an array is just a pointer to the first member memory location. I have no idea how java script works. I think it would work in c, not even sure about that. Anyway, I was just musing.
     
  10. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Unity does not use C, so that's irrelevant. Even if it did, the float is used to launch the function at a specific time, it's not passed to it, as I mentioned.

    --Eric
     
    visionnaireMedia likes this.
  11. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    Yeah, I saw that. Haven't used it yet. Interesting that it wouldn't actually be used in the function, I almost feel cheated. I'm just learning Unity and mainly reading the boards for that purpose.
     
  12. Tanel

    Tanel

    Joined:
    Aug 31, 2011
    Posts:
    508
    Well, it's used in the Invoke method to determine when to call your method, so no need to feel cheated, it's still being used.
     
  13. RishBee

    RishBee

    Joined:
    Sep 21, 2014
    Posts:
    3
    I wish they supported it.
    In my situation, I need to invoke functions according to a object's type:
    Code (CSharp):
    1. System.Type myType=Object.GetType();
    2.  
    3. Invoke("Load"+myType.Name,0);
    4.  
    5. void LoadType1()
    6. {}
    And pass parameters to the LoadType(n) function, still wondering if there might be any workaround for this
     
    Maskeowl likes this.
  14. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    974
    The Unity framework GameObject.Invoke method does not accept parameters, however the .net framework does support this via MethodBase.Invoke

    First you'll need to get the correct MethodInfo, which you can access from your type. Assuming the method is on the class calling this code:
    Code (csharp):
    1. var loadingMethod = this.GetType().GetMethod("Load"+myType.Name);
    Next, put the arguments you need to send into an array of objects:
    Code (csharp):
    1. var arguments = new object[] { arg1, arg2 };
    Finally, invoke the method on this object with the arguments:
    Code (csharp):
    1. loadingMethod.Invoke(this, arguments);
     
    blurg, luigi7, gameogami and 6 others like this.
  15. RishBee

    RishBee

    Joined:
    Sep 21, 2014
    Posts:
    3
    That works !
    Thanks for the great suggestion.
     
  16. demonpants

    demonpants

    Joined:
    Oct 3, 2008
    Posts:
    82
    In my case, I was getting network requests coming back on a different thread, so I needed a way to push the results back to the main thread (messing with Unity objects in another thread was causing wacky results). I solved this with an array of pending functions that got cleared in Update(), like this.

    Code (CSharp):
    1. using System;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Invoker : MonoBehaviour
    6. {
    7.     private struct PendingInvoke
    8.     {
    9.         public Action<object[]> invoke;
    10.         public object[] parameters;
    11.  
    12.         public PendingInvoke(Action<object[]> invoke, object[] parameters)
    13.         {
    14.             this.invoke = invoke;
    15.             this.parameters = parameters;
    16.         }
    17.  
    18.         public void Invoke()
    19.         {
    20.             this.invoke(this.parameters);
    21.         }
    22.     }
    23.  
    24.     private static Invoker instance;
    25.     public void Awake()
    26.     {
    27.         if (instance != null && instance != this)
    28.         {
    29.             Destroy(gameObject);
    30.             return;
    31.         }
    32.         instance = this;
    33.         DontDestroyOnLoad(gameObject);
    34.     }
    35.  
    36.     private List<PendingInvoke> pendingInvokes = new List<PendingInvoke>();
    37.  
    38.     public static void Add(Action<object[]> invoke, object[] parameters)
    39.     {
    40.         instance.pendingInvokes.Add(new PendingInvoke(invoke, parameters));
    41.     }
    42.  
    43.     private void Update()
    44.     {
    45.         foreach(PendingInvoke invoke in pendingInvokes)
    46.         {
    47.             invoke.Invoke();
    48.         }
    49.         pendingInvokes.Clear();
    50.     }
    51. }
    52.  
    Code (csharp):
    1.  
    2. /////example
    3. public void InvokedAddFunction(object[] parameters)
    4. {
    5.     Debug.Log(((int)parameters[0]) + ((int)parameters[1]));
    6. }
    7.  
    8. public void Start()
    9. {
    10.     //instead of Invoke(target,"InvokedAddFunction")...
    11.     //the following will print "13" in the next update
    12.     Add(InvokedAddFunction, new object[]{5, 8});
    13. }
    Also, even though it's years later, for any who stumble on this thread I really want to reply to what fire7side said above about arrays and floats. He's completely wrong on all fronts – in C#, types are strict and so there is a major difference between an array and a float. In fact, I think in every single language I can think of, that's the case in terms of how they're stored in memory. When he's talking about them being the same in C, he's referring to arrays being chunks of continuous memory that have a single integer pointer to where they start (hence you needing to manually keep track of their length). A floating point number (float) is completely different. So don't take that post as anything real!
     
  17. unity2life

    unity2life

    Joined:
    Jun 6, 2020
    Posts:
    19
    I'm new to C# and come from Java programming. Is that what u do corresponding to Java's reflection mechanism?
     
    Fumetsujo likes this.
  18. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    974
    I'm not familiar with Java, but yes, this is known as reflection. It comes with some caveats, such as slower performance and may not work at all in scenarios that don't support just-in-time compiling.
     
  19. Giantbean

    Giantbean

    Joined:
    Dec 13, 2012
    Posts:
    144
  20. hwesta

    hwesta

    Joined:
    Jan 20, 2014
    Posts:
    1
    easily you can make another method that calls method with parameter. and you can invoke caller method

    ...
    Invoke ("CallMyMethod", 1f);
    ...

    void CallMyMethod()
    {
    MyMethodWithParams(10f, 5f, "lots of diffetrent params");
    }
     
  21. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    But what if the parameter values are contextual?

    I think the best advice to give someone trying to use Invoke is "don't"...
     
    Bunny83 and Kurt-Dekker like this.
  22. Maskeowl

    Maskeowl

    Joined:
    Apr 24, 2021
    Posts:
    8
    Thank you YOU are life Saver THX A LOT
     
  23. Jesupez

    Jesupez

    Joined:
    Mar 19, 2023
    Posts:
    1
    You can make a variable and modifie it before you invoke and use it in the function
     
  24. MoLavaie

    MoLavaie

    Joined:
    Feb 19, 2019
    Posts:
    12
    the Invoke the OP is talking about derives from MonoBehaviour, it is not related to events. It has also another variant called InvokeRepeating.
     
    Giantbean likes this.