Get Property Type and value from another script without knowing it

Hello. This is my first post here so i’m sorry if I made any mistake. Have been playing with unity + csharp for some time, learning and trying to understand. This week I`m stuck with something beyond my knowledge.

The objective is return the value of a public field that is on script component of game object. I have already managed to get it with gameobject.getcomponent(component).field . But on this challenge, I don’t have the component name, and the field name. So, I came around this

public static class GetObjectProperties
{
    public static List<string> GetProps(GameObject obj)
    {
        List<string> PropertiesList = new List<string>();
        GameObject Object = obj;
        FieldInfo[] fields;
        Component[] Components = obj.GetComponents(typeof(Component));
        foreach (var comp in Components)
        {
            fields = comp.GetType().GetFields();
            foreach (var fi in fields)
            {
                PropertiesList.Add(fi.ToString());
            }
        }
        return PropertiesList;
    }

This returns a list of the “Properties” (it is the correct name of it?). Cool. It does not show the Unity Base properties of its components transform and box collider. Perfect!
5143595--509216--upload_2019-11-5_23-5-37.png 5143595--509219--upload_2019-11-5_23-10-8.png
5143595--509216--upload_2019-11-5_23-5-37.png

So, I tried to expand from this point, but can’t figure out the correct way of doing it.

I can, for example have a list of all the known components and game some kind of “if” with this
like:

5143595--509219--upload_2019-11-5_23-10-8.png

and after it, creating by hand the “known” properties / field names but it will not be “plug n play” like it should.

I wish something like:

public static var GetObjectFieldValue (GameObject obj, string fieldName)
{
//cycle to all available field and the the match field that i`m looking for and return the value if it exists
}

I know it may seem odd. Its for a system that builds a custom UI based on a selected object with I can already know and also serve for objects that I don’t have scripted yet.

Any help will be appreciated.

I’m not sure I fully understand your question. To me it seems that you already have all the Information you are looking for. If you look at your Object Properties List, they contain both type and name of each attribute, e.g. ‘System.String Name’. What exactly are you looking for?

I’m missing the value…

Ah. Something like this

 public static object GetPropValue(object src, string propName)
{
     return src.GetType().GetProperty(propName).GetValue(src, null);
}

That’s from stackoverflow, btw. You’ll find a lot more interesting info if you Google ‘c# reflection unity’.

1 Like

Thank you very much!