Search Unity

Calling functions with parameters from a string array

Discussion in 'Scripting' started by DeLannoy04, Nov 25, 2019.

  1. DeLannoy04

    DeLannoy04

    Joined:
    Jul 2, 2019
    Posts:
    42
    Hi,
    I have a string array and I need to call functions using those strings + I need to give some parameter to it(like I have a method: SetSpawn(transform tr) and a string: "SetSpawn".
    What would be the best way to solve it?
    Thank you for the answers!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,752
    I'm unclear what you're trying to do.

    Can you just use a for() loop to iterate all the strings and call whatever method you want?

    Or do you want to just use Random.Range() to select one of the strings randomly, and use that one?
     
  3. DeLannoy04

    DeLannoy04

    Joined:
    Jul 2, 2019
    Posts:
    42
    My problem is that I want to add parameters to them, and that is impossible by using Invoke.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,752
  5. DeLannoy04

    DeLannoy04

    Joined:
    Jul 2, 2019
    Posts:
    42
    I found it as well, but those solutions don't solve my issue since I need to call functions from a string array.
     
  6. JeffDUnity3D

    JeffDUnity3D

    Joined:
    May 2, 2017
    Posts:
    14,446
    ButtonActionClass.Invoke(FunctionNames[1],FunctionDelayTime);
     
  7. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    Just to check: is there a reason the original array identifying the functions that you want to call is using strings instead of delegates?
     
  8. DeLannoy04

    DeLannoy04

    Joined:
    Jul 2, 2019
    Posts:
    42
    But you cannot give parameters to a function using invoke
     
  9. DeLannoy04

    DeLannoy04

    Joined:
    Jul 2, 2019
    Posts:
    42
    Thanks, I never heard about that :D
    By the way, the only problem with it that I can only use that type of variable I set when declaring the delegates. I know, I can dodge it by a setting a string parameter so I can transform that almost to anything, but is there any better solution?
     
  10. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,331
    Just have your parameter be of type object. Or object[], if you need to support multiple parameters.

    Code (CSharp):
    1. Action<object> example = (x)=>Debug.Log(x.ToString());
    2. example(10f);
    3. example("hello!");
     
  11. DeLannoy04

    DeLannoy04

    Joined:
    Jul 2, 2019
    Posts:
    42
    Thank you
     
    SisusCo likes this.