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

Question GetType.GetField.GetValue from another script as GameObject

Discussion in 'Scripting' started by dublajar, Jul 23, 2023.

Thread Status:
Not open for further replies.
  1. dublajar

    dublajar

    Joined:
    Apr 24, 2023
    Posts:
    12
    So i have been trying to reach a GameObject type variable located inside of another script, since the Obj / SellPrice / BuyPrice will need to be reached of the given item i am trying to use the GetType method. here is the code

    Code (CSharp):
    1. GameObject var = (GameObject)gameManager.itemData.GetType().GetField(pickedItems[0]+"Obj").GetValue(this);
    if i write this like:
    Code (CSharp):
    1. gameManager.itemData.WaterObj;
    it tottaly works fine

    here is item data:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class ItemsData : MonoBehaviour
    6. {
    7.     public GameObject WaterObj;
    8.     public float WaterBuy = 0.8f;
    9.     public float WaterSell = 1.2f;
    10.  
    11.     public GameObject CerealObj;
    12.     public float CerealBuy = 2f;
    13.     public float CerealSell = 4.5f;
    14. }
    15.  

    it gives out the error: Assets\Scripts\Customers\Customer.cs(139,117): error CS0119: 'GameObject' is a type, which is not valid in the given context

    please help. . .
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,954
    Errors in general:

    The complete error message contains everything you need to know to fix the error yourself.

    The important parts of the error message are:

    - the description of the error itself (google this; you are NEVER the first one!)
    - the file it occurred in (critical!)
    - the line number and character position (the two numbers in parentheses)
    - also possibly useful is the stack trace (all the lines of text in the lower console window)

    Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

    Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly?

    All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don't have to stop your progress and fiddle around with the forum.

    Remember: NOBODY here memorizes error codes. That's not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

    Referencing variables, fields, methods (anything non-static) in other script instances:

    https://forum.unity.com/threads/hel...-vars-in-another-script.1076825/#post-6944639

    https://forum.unity.com/threads/accessing-a-gameobject-in-different-scene.1103239/

    It isn't always the best idea for everything to access everything else all over the place. For instance, it is BAD for the player to reach into an enemy and reduce his health.

    Instead there should be a function you call on the enemy to reduce his health. All the same rules apply for the above steps: the function must be public AND you need a reference to the class instance.

    That way the enemy (and only the enemy) has code to reduce his health and simultaneously do anything else, such as kill him or make him reel from the impact, and all that code is centralized in one place.
     
  3. dublajar

    dublajar

    Joined:
    Apr 24, 2023
    Posts:
    12
    yeah doesent explains anything
     
  4. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,184
    var
    is a keyword. You can't use keywords as variable or method names.
     
    Kurt-Dekker and Chubzdoomer like this.
  5. dublajar

    dublajar

    Joined:
    Apr 24, 2023
    Posts:
    12
    thanks alot but can you also maybe say what i have to do. So sorry
     
  6. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,184
    Choose a different variable name.
     
    Kurt-Dekker likes this.
  7. dublajar

    dublajar

    Joined:
    Apr 24, 2023
    Posts:
    12
    aight
     
  8. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,954
    Steps to success:

    - describe to yourself exactly what you are trying to do

    - look on Youtube for tutorials to do the individual parts

    - understand those tutorials

    - use the understanding to engineer your solution

    Your comments above seem to indicate you might be unclear on the concepts of learning new technical things.

    Below is a simple two-step process that never fails if applied diligently:

    Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

    How to do tutorials properly, two (2) simple steps to success:

    Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That's how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.

    Fortunately this is the easiest part to get right: Be a robot. Don't make any mistakes.
    BE PERFECT IN EVERYTHING YOU DO HERE!!


    If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

    Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

    Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

    Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there's an error, you will NEVER be the first guy to find it.

    Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

    Finally, when you have errors, don't post here... just go fix your errors! Here's how:

    (what I posted above, I won't insult you by posting it a second time. Hopefully you'll read it this time).
     
  9. dublajar

    dublajar

    Joined:
    Apr 24, 2023
    Posts:
    12
    ArgumentException: Field CerealObj defined on type ItemsData is not a field on the target object which is of type Customer.
    Parameter name: obj
    System.Reflection.RuntimeFieldInfo.GetValue (System.Object obj) (at <d6232873609549b8a045fa15811a5bd3>:0)
    Customer.Update () (at Assets/Scripts/Customers/Customer.cs:139)
     
  10. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,954
    Nothing has changed about the steps to fix an error since when I posted it the first time an hour ago.

    Are you able to explain why you are using reflection?

    If not then you should not be using reflection.

    If you're not even aware that you are using reflection... well I'm not sure what to advise.

    If you are hell-bent on using reflection... then...

    The complete error message contains everything you need to know to fix the error yourself.

    The important parts of the error message are:

    - the description of the error itself (google this; you are NEVER the first one!)
    - the file it occurred in (critical!)
    - the line number and character position (the two numbers in parentheses)
    - also possibly useful is the stack trace (all the lines of text in the lower console window)

    Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

    Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly?

    All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don't have to stop your progress and fiddle around with the forum.

    Remember: NOBODY here memorizes error codes. That's not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.
     
  11. dublajar

    dublajar

    Joined:
    Apr 24, 2023
    Posts:
    12
    Gosh this is not helping stop the copy paste please god please
     
    kdchabuk and Kurt-Dekker like this.
  12. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,184
    Speaking of which here is how you would implement it without reflection:
    Code (CSharp):
    1. using System.Collections.Generic;
    2. using UnityEngine;
    3.  
    4. public class ItemsData : MonoBehaviour
    5. {
    6.     [System.Serializable]
    7.     public struct Item
    8.     {
    9.         public string Name;
    10.         public GameObject GameObject;
    11.         public float BuyPrice;
    12.         public float SellPrice;
    13.     }
    14.  
    15.     public List<Item> items = new List<Item>();
    16.  
    17.     public Item GetItemByName(string name)
    18.     {
    19.         for (var index = 0; index < items.Count; index++)
    20.         {
    21.             if (items[index].Name == name)
    22.             {
    23.                 return items[index];
    24.             }
    25.         }
    26.     }
    27. }
    Example:
    Code (csharp):
    1. GameObject go = gameManager.itemData.GetItemByName(pickedItems[0]).GameObject;
    Here's what it looks like in the editor (was too lazy to hook up GOs):
    upload_2023-7-23_18-11-8.png
     
    Last edited: Jul 23, 2023
    Kurt-Dekker likes this.
  13. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,572
    This shows you use reflection without understanding what this actually does.

    This part
    Code (CSharp):
    1. gameManager.itemData.GetType()
    Just gets your the System.Type object that describes that type / the class of the object stored in "itemData". This System.Type object has no connection to the actual instance that is stored in your itemData variable, it's only the type description. You then get a field definition from that type with
    Code (CSharp):
    1. .GetField(pickedItems[0]+"Obj")
    Which gives you a FieldInfo that again generally describes the field of the type. It has no connection to any particular instance of a class.

    Finally you do this:
    Code (CSharp):
    1. .GetValue(this);
    and there's your mistake. GetValue actually tries to get the value of that field from an object instance. However you pass in "this" as object instance. I'm pretty sure that the field you try to access does not belong to this object, does it? Since you got the type from "gameManager.itemData", you probably wanted to get the value from that object, right?

    Just to make that clear. When you do this:
    Code (CSharp):
    1. gameManager.itemData.GetType()
    you actually get the same as doing

    Code (CSharp):
    1. typeof(ItemsData)
    Of course your case does get the type dynamically, in case some other type may be stored in that variable. However when you know the type of the object stored in that variable, you can also use typeof with the class / type name instead. That FieldInfo you get from the type also does never change and can be used for any instance of that type.

    So what you should have done would be

    Code (CSharp):
    1.  
    2. var itemDataType = gameManager.itemData.GetType();
    3. var fieldInfo = itemDataType.GetField(pickedItems[0]+"Obj")
    4. GameObject obj = (GameObject)fieldInfo.GetValue(gameManager.itemData); // get this field from the object in "gameManager.itemData"
    5.  
    Though as others have pointed out, you shouldn't rely on reflection for things like that. Your whole architechture represents a bad design. You try to use concept from loosly typed / dynamically typed scripting languages in C#.

    What @Ryiah posted is the way to go. That's one of the points of OOP. Create objects which group things together which belong together.

    If you will have hundreds of "items" defined in that list, you can also create a Dictionary that you simply initialize in Awake so you can more easily look up a certain item by it's name. However if you only have like 10-30 items it's probably not worth it. This for loop iterating through the list is most likely 10 times faster as that reflection approach.
     
    Ryiah likes this.
  14. zombiegorilla

    zombiegorilla

    Moderator

    Joined:
    May 8, 2012
    Posts:
    9,002
    Bunny83 likes this.
Thread Status:
Not open for further replies.