Problem with getting all the properties of an object

I understand that I can iterate through a list of properties with

object.GetType().GetProperties();

However, that doesn’t seem to work here. I’m fairly new to C# and unity, so I know I’m definitely missing something obvious, but anything helps. Thanks!

Class:

public class PlayerPreferences_Audio
{
    public float MasterVolume = 1.0f; // Master
    public float MusicVolume = 1.0f; // Music
    public float PlayerVolume = 1.0f; // Player Noises
}

public class PlayerPreferences
{
    public PlayerPreferences_Audio Audio;

    public PlayerPreferences()
    {
        Audio = new PlayerPreferences_Audio();
    }
}

Code:

PlayerPreferences testPlayerPreferences = new PlayerPreferences();

Debug.Log(testPlayerPreferences.Audio.MasterVolume);
Debug.Log(testPlayerPreferences.GetType().GetProperties().Length);

image

Why is it telling me the object has no properties even though I am directly accessing one in that code?

Because your PlayerPreferences_Audio has three fields, not properties.

You would use Type.GetFields() to get these member instead: Type.GetFields Method (System)

Though should you really be using reflection for this?

2 Likes

That worked out for me, thanks!

What alternative processes can I perform that may work better?

You could make the class serializable, serialize it to json, and write it to disk. Some further reading here:

Namely you can write the object to json, and save it as a text file somewhere in the Application.persistantDataPath to be read from later.