Search Unity

Calling functions with parameters from a string array

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

  1. NanduCubeGm

    NanduCubeGm

    Joined:
    Jul 2, 2019
    Posts:
    35
    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:
    5,023
    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. NanduCubeGm

    NanduCubeGm

    Joined:
    Jul 2, 2019
    Posts:
    35
    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:
    5,023
  5. NanduCubeGm

    NanduCubeGm

    Joined:
    Jul 2, 2019
    Posts:
    35
    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

    Unity Technologies

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

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    1,695
    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. NanduCubeGm

    NanduCubeGm

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

    NanduCubeGm

    Joined:
    Jul 2, 2019
    Posts:
    35
    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:
    356
    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. NanduCubeGm

    NanduCubeGm

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