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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

TargetParameterCount Exception

Discussion in 'Scripting' started by IL4Mi3y, May 28, 2015.

  1. IL4Mi3y

    IL4Mi3y

    Joined:
    Dec 29, 2014
    Posts:
    38
    I use this code to dynamically invoke a getter from a transform component.
    Code (CSharp):
    1.  
    2. public delegate T1 GenericGet<T1>(Transform t);
    3. private static System.Delegate createdDelegate;
    4.  
    5. public void Init()
    6. {
    7.     PropertyInfo[] infos = typeof(Transform).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    8.     foreach (PropertyInfo info in infos)
    9.     {
    10.         // Save getter
    11.         MethodInfo method = info.GetGetMethod();
    12.  
    13.         System.Type returnType = method.ReturnType;
    14.         //System.Type paramType = method.GetParameters()[0].GetType();
    15.  
    16.         System.Type newType = typeof(GenericGet<>).MakeGenericType(returnType);
    17.         createdDelegate = System.Delegate.CreateDelegate(newType, method);
    18.        
    19.         //var instance = System.Activator.CreateInstance(newType);
    20.  
    21.         var obj = createdDelegate.DynamicInvoke(this.Value);
    22.     }
    23. }
    This code works perfectly in a .NET project. (VS)
    But in Unity I got a TargetCount Exception. (line 17)

    I tried many things, but none of them works.
    Do you have some idea to solve it?

    I'm shocked that it works in a .NET project.
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    might be that this is something that works with more recent .NET framework version? i think unity is still on .NET 2.0...
     
    IL4Mi3y likes this.
  3. IL4Mi3y

    IL4Mi3y

    Joined:
    Dec 29, 2014
    Posts:
    38
    @LeftyRighty This could be a possible reason.
    But I changed the Freamework version down to 2.0 and it stills works in VS.

    I also tried to change it to Unity 3.5 .NET and it works too.
     
  4. IL4Mi3y

    IL4Mi3y

    Joined:
    Dec 29, 2014
    Posts:
    38
    When I use
    Code (CSharp):
    1. var invoked = method.Invoke(this.Value, new object[0]);
    2. System.Convert.ChangeType(invoked, method.ReturnType);
    3. Debug.Log("Invoke " + invoked);
    it also works.
    But I don't want to save the whole MethodInfo object, I only want the delegate.