Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

GetMethod invocation doesn't work

Discussion in 'Scripting' started by asidjasidjiasd, Feb 16, 2020.

  1. asidjasidjiasd

    asidjasidjiasd

    Joined:
    Feb 9, 2020
    Posts:
    12
    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System.Reflection;
    5. using UnityEngine;
    6.  
    7.  
    8. public class testing : MonoBehaviour
    9. {
    10.  
    11.     public int sqr(params object[] data)
    12.     {
    13.         int num = (int)data[0];
    14.         return num * num;
    15.     }
    16.  
    17.  
    18.     void Start()
    19.     {
    20.         Type t = this.GetType();                
    21.         MethodInfo mi = t.GetMethod("sqr");
    22.         Debug.Log(mi);                  // Int32 sqr(System.Object[])
    23.  
    24.         int result = (int)mi.Invoke(this, new object[] { 4 });
    25.         // ArgumentException: Object of type 'System.Int32' cannot be converted to type 'System.Object[]'.
    26.  
    27.         Debug.Log(result);
    28.     }
    29.  
    30.  
    31. }
    I could invoke it directly but the question is not how I do it, but why this approach doesn't work. I'm trying to save a function into a variable and then execute it afterwards. I know about alternate solutions like Action, delegate and Func, but I'm interested in getting this to work with this approach.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    Found it! I think you have to double-wrap your input. Check the docs here:

    https://docs.microsoft.com/en-us/do...ction.methodbase.invoke?view=netframework-4.8

    I quote:

    "This is an array of objects with the same number, order, and type as the parameters of the method or constructor to be invoked."

    I tried this double-wrapping code and it worked:

    Code (csharp):
    1.         var rawargs = new object[] { 4};
    2.         var packed = new object[] { rawargs};
    3.         var result = (int)mi.Invoke( this, packed);
    4.         Debug.Log(result);
    Screen Shot 2020-02-16 at 11.12.28 AM.png

    Basically the outer array is a single entry array, the first entry being the array of args passed into the call.

    This lets that first entry match an array of object[] for your first argument in your sqr() call.

    Whew. Now I'm going to go reflect on that a bit... :)
     
    asidjasidjiasd likes this.
  3. asidjasidjiasd

    asidjasidjiasd

    Joined:
    Feb 9, 2020
    Posts:
    12
    ha ha . . .

    Anyways, thank you very much. That solves insane amount of problems.
     
    Kurt-Dekker likes this.