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

Resolved ArgumentException on Set/GetValue?

Discussion in 'Scripting' started by CassioTDS, Nov 21, 2021.

  1. CassioTDS

    CassioTDS

    Joined:
    Jan 21, 2020
    Posts:
    12
    Hey, so when doing:
    Code (CSharp):
    1.  
    2. foreach (KeyValuePair<string, object> entry in values)
    3.     {
    4.         try
    5.             {
    6.                 var typeofVar = typeof(VariableStorer);
    7.                 print(typeofVar.GetField(entry.Key).SetValue(typeofVar,entry.Value);
    8.             }
    9.             catch(Exception e)
    10.             {
    11.                 print(entry.Key+" HAS "+e);
    12.                 problems = problems +entry.Key + "/";
    13.             }
    14.         }
    I get
    "System.ArgumentException: Field langugagePath defined on type VariableStorer is not a field on the target object which is of type System.RuntimeType.Type"
    Any help please?
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    The first parameter in the
    SetValue
    method expects an actual object instance of your
    VariableStorer
    type. You can't set a member on the type, because the type is just the definition of the object, not an instance of it. The program needs to know which instance of the
    VariableStorer
    type you want to access, since there could be many instances.
     
    CassioTDS and Bunny83 like this.
  3. CassioTDS

    CassioTDS

    Joined:
    Jan 21, 2020
    Posts:
    12
    So basically, I should do
    [game object].GetComponent<VariableStorage>()
    ?
     
  4. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    If it's a MonoBehaviour, yes.
    Code (CSharp):
    1. VariableStorage vs = gameObject.GetComponent<VariableStorage>();
    2. vs
    3.   .GetType()
    4.   .GetField(entry.Key)
    5.   .SetValue(vs, entry.Value);
    (I'm also assuming "VariableStorage" is the same type renamed from "VariableStorer" here.)
     
    Last edited: Nov 21, 2021
    CassioTDS likes this.
  5. CassioTDS

    CassioTDS

    Joined:
    Jan 21, 2020
    Posts:
    12
    Thank you, and your assumption is right.