Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
3
Question by Dray · Nov 03, 2015 at 12:14 AM · listserializationvariablesclassproperties

How to get a List of all Variables in a Class

So I defined a data-holder class that contains a big number of primitive variables. For simplicity let's say the class looks something like this:

 public class Properties {
         bool aBool;
         float someFloat;
         int anInteger;
 }

I want to be able to attach any event to a set of conditions. As sourcecode this would look something like this:

 public void CheckConditions(Properties properties) {
     if (properties.aBool == true) {
         //Run any Event
     }
 }

I don't want to define those Conditions inside my source code for several reasons: - The Conditions should be editable in a custom Editor window, without the need to touch any sourcecode. - Sets of Conditions should be saved into and loaded from files.

So I started creating condition-classes for every variable inside the "Properties" class which became kind of confusing pretty fast.

Now I'm trying to figure a generic way to read out a list of all the variable names and their types defined in the dataholder class inside my sourcecode so i can define something like "Every number value can be checked for an input value being bigger, smaller, equal or unequal" and show these options in my UI. Later I want to be able to create condition-sets for pre-defined events in my Script without the need of defining a new variable in 5 different locations everytime a new one is created.

Shortly, I'm looking for a function that outputs all the variables inside the data-holder class as string-array for example.

And I need another function that gets the value inside the variable that matches the given (string) variable name.

I imagine something like this:

 public struct Variable {
     string name;
     Type type;
 }
 
 public class Properties {
     public Variable getVairables() {
         // ... ?
     }
 
     public T getValue<T>(string varName) {
         // ... ?
     }
 }


I wonder if Serializing is the right direction here, I saw some functions that seam to deal with - let me call it "variable variables" - but I'm not sure about that though.

Any suggestions on how to achive this are very welcome! If this question has been answered allready please redirect me to any sources.

Thank you! And sorry for the lack of english skills ;)

Comment
Add comment · Show 5
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Arycama · Nov 03, 2015 at 07:11 AM 1
Share

You'd have to use C# Reflection. I'm not sure on the details exactly, but that would be a good place to start.

avatar image Pangamini Arycama · Nov 03, 2015 at 01:33 PM 0
Share

just a note, reflection is in no way related to the language

avatar image Arycama Pangamini · Nov 03, 2015 at 03:43 PM 1
Share

How is reflection not related to the language?

This is pretty much exactly what the question is asking for, and someone else has also commented below:

http://www.dotnetperls.com/reflection-field

Show more comments
avatar image fafase · Nov 03, 2015 at 08:44 AM 1
Share

$$anonymous$$aybe this could be guiding you : https://unitygem.wordpress.com/json-serializer-attributes-reflection/

Go down to the reflection section. It is using attributes but the principle remains the same:

    Type type = typeof($$anonymous$$yClass);
    FieldInfo [] infos = type.GetFields();
    foreach(FieldInfo fi in infos){ }

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Dray · Nov 03, 2015 at 08:55 PM

Allright, thanks for your answers! In the end, the perfect conclusion for me is using the Type class, which serves functions for exactly what I want to achieve.

This function gives me all the Properties according to the Type that I pass to it using "myObject.GetType()":

         public static Variable[] getProperties(Type type) {        
             var propertyValues = type.GetProperties ();
             var result = new Variable[propertyValues.Length];
             for (int i = 0; i < propertyValues.Length; i++) {            
                 result[i].name = propertyValues[i].Name;
                 result[i].type = propertyValues[i].GetType();
             }
             
             return result;
         }

And I use these Functions to read or write a values:

         public object getValue(string name) {            
             return this.GetType().GetProperty(name).GetValue(this,null);
         }
 
         public void setValue(string name, object value) {
             this.GetType().GetProperty(name).SetValue(this,value,null);
         }

In my case I need the Objects Properties. You can also read Fields using "getFields()" instead and I read about some different ways to get public / private / etc. values but I closed the Tab allready and can't find the resource anymore. Sorry for that. Still I think it's good to know that they are there.

For those who are interested in this, here is a full class that provides functions to solve this Problem:

 using System;
 
 
 public class PropertyReader {
 
     //simple struct to store the type and name of variables
     public struct Variable {
         public string name;
         public Type type;
     }
 
     //for instances of classes that inherit PropertyReader
     private Variable[] _fields_cache;
     private Variable[] _props_cache;
     
     public Variable[] getFields() {
         if (_fields_cache == null)
             _fields_cache = getFields (this.GetType ());
         
         return _fields_cache;
     }
     
     public Variable[] getProperties() {
         if (_props_cache == null)
             _props_cache = getProperties (this.GetType ());
         
         return _props_cache;
     }
 
     //getters and setters for instance values that inherit PropertyReader
     public object getValue(string name) {            
         return this.GetType().GetProperty(name).GetValue(this,null);
     }
     
     public void setValue(string name, object value) {
         this.GetType().GetProperty(name).SetValue(this,value,null);
     }
 
     //static functions that return all values of a given type
     public static Variable[] getFields(Type type) {
         var fieldValues = type.GetFields ();
         var result = new Variable[fieldValues.Length];        
         for (int i = 0; i < fieldValues.Length; i++) {
             result[i].name = fieldValues[i].Name;
             result[i].type = fieldValues[i].GetType();
         }
         
         return result;
     }
     
     public static Variable[] getProperties(Type type) {        
         var propertyValues = type.GetProperties ();
         var result = new Variable[propertyValues.Length];
         for (int i = 0; i < propertyValues.Length; i++) {            
             result[i].name = propertyValues[i].Name;
             result[i].type = propertyValues[i].GetType();
         }
         
         return result;
     }
 }

From the outside I call it like this:

 PropertyReader.getProperties(typeof(AnyClass));

Or I inherit PropertyReader into another Class like this

 public class MyProperties : PropertyReader {
     bool aBool;
         float someFloat
         //...
 }

Surely still needs to be optimized but that's the direction I took. Thanks for your help guys!

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Straafe · Apr 24, 2018 at 11:53 PM 0
Share

Just wanted to let you know I found your solution useful

avatar image Zehs · Jan 18, 2021 at 10:53 AM 0
Share

@Dray I have no idea how to use this. I'm trying to get variables from a script and I want to check which ones are floats, bools, and other. Please help

avatar image Pangamini Zehs · Jan 19, 2021 at 04:14 PM 0
Share

System.Type is a class. You can take any object in c# and call it's method GetType() that returns it's type. Here's $$anonymous$$SDN for it: System.Type. You can use its GetFields() method to get all fields (which you call variables) of your type. Then, you can check of what type those fields are, what is it's name, attributes, etc.

avatar image peter_unity996 · May 25, 2021 at 08:43 AM 0
Share

Don't forget to add the BindingFlags field in GetProperty() for parameters that are private, internal or protected! You will need to include BindingFlags.NonPublic eg. this.GetType().GetProperty("name", BindingFlags.NonPublic).SetValue(this, value);

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

10 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

object assigns but does not show when added to list, or any other var 0 Answers

Property drawer stops variables from being read 0 Answers

How do I save an array of all different variables? 0 Answers

A node in a childnode? 1 Answer

Difference between assigning a value in inspector and with a custom editor script 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges