Dan Tang
Dan Tang

Reputation: 1333

Accessing fields in Unity C# classes (not sure how to do reflection properly)

I have a class DataHolder that stores different Lists, and I have a function that updates a dropdown if the courses List is initialised. I have different types of Lists (e.g. course, student) and different functions to check for each type. I would like to create a generic function that works for different types of Lists, and the main hold up is I'm not sure how to dynamically access field names in C# using strings. I was reading up on reflection but can't seem to get it to work.

Basically, I'm looking for a C# equivalent of dataHolder[dataType] != null && dataHolder[dataType].length.

Reflection

private DataHolder dataHolder;

void CheckIfCoursesHasBeenPulled (string dataType) {
    //dataHolder has been initialised in Start function
    if (dataHolder.courses != null && dataHolder.courses.Count > 0) {
        UpdateDropdown(dataHolder.courses);
    }

    //code that I hope to do but getting error
    if (dataHolder.GetType().GetField(dataType).GetValue(dataHolder) != null && dataHolder.GetType().GetField(dataType).GetValue(dataHolder).Count > 0) {
        UpdateDropdown(dataHolder.courses);
    }
}

Error Message

Operator ‘>’ cannot be applied to operands of type ‘method group’ and ‘int’

Upvotes: 0

Views: 65

Answers (1)

Doug
Doug

Reputation: 35136

GetValue returns an object; you need to cast it to a List or something to be able to use Count on it.

eg.

using System.Collections.Generic;

namespace Assets.Foo
{
  public class DataHolder
  {
    public List<object> courses;
  }

  public class Class1
  {
    private DataHolder dataHolder;

    void CheckIfCoursesHasBeenPulled (string dataType) {
      //dataHolder has been initialised in Start function
      if (dataHolder.courses != null && dataHolder.courses.Count > 0) {
        UpdateDropdown(dataHolder.courses);
      }

      // Convert object to object[] or List<Foo> or whatever here...
      var objects = dataHolder.GetType().GetField(dataType).GetValue(dataHolder) as List<object>;
      if (objects != null && objects.Count > 0) {
        UpdateDropdown(dataHolder.courses);
      }
    }

    private void UpdateDropdown(List<object> dataHolderCourses)
    {
      throw new System.NotImplementedException();
    }
  }
}

Upvotes: 1

Related Questions