x


Unity Reflection / class member listing

Okay, so suppose I've got a class with a bunch of members like this:

class MyClass {
  var classMemberOne:int;
  var anotherClassMember:float;
  function MyClass() {
    classMemberOne = 5;
    anotherClassMember = 2.3;
  }
}

I want a function listMembers(myobj) that will list the members in it like this.

var myobj:MyClass = new MyClass();
Debug.Log(listMembers(myobj)); // Should print 'classMemberOne' 'anotherClassMember' to the log.

If I made another class or passed in an existing class, it should do the same thing, regardless of the class. This seems incompatible with strict typing (how do you specify the type of input to a function like that?) but I feel confident that there's some way around it.

Any thoughts?

more ▼

asked May 11 '12 at 04:45 AM

natosaichek gravatar image

natosaichek
0 1 1 1

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

Here. However, this is in C# so you have to convert it to Javascript, but it should work.

static string listmembers(Object obj)
    {
        StringBuilder result = new StringBuilder();
        FieldInfo[] fields = obj.GetType().GetFields();
        foreach (FieldInfo field in fields)
        {
            result.Append("'" + field.Name + "' ");
        }
        return result.ToString();
    }
more ▼

answered May 11 '12 at 02:18 PM

raoz gravatar image

raoz
376 3 6 8

This ought to be correct. Maybe some simple errors

using System.Text;
using System.Reflection;

function listmembers(obj : Object) : string
    {
        var result : StringBuilder = StringBuilder();
        var fields : FieldInfo[] = obj.GetType().GetFields();
        for(var field in fields)
        {
            result.Append("'" + field.Name + "' ");
        }
        return result.ToString();
    }
May 11 '12 at 02:29 PM raoz
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

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

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x140
x125
x5

asked: May 11 '12 at 04:45 AM

Seen: 1100 times

Last Updated: May 11 '12 at 02:30 PM