Check if class exists and invoke its method

I am writing a plugin that needs check exists of other class (NGUI etc.) and access its attribute or invoke method.

For example what I need to do is to set UILabel attributes and invoke its method.

UILabel label = gameObject.GetComponent<UILabel>();

// Access attribute
label.text = "hello world";

// Invoke Method
label.MakePixelPerfect();

While another project, I have plugin to check presence of UILabel, if it exists it will change it’s attribute or invoke it’s method, else ignore it. Here’s the code I got stuck:

Type label = System.Type.GetType("AudioListener");
if(label != null){

	// How do I access it's attribute?

	// How do I invoke function?
}

So, my question would be how to check if the class exists and change its attribute or invoke its method if class exists.

Thank you

GetComponent is a also method of Component. http://msdn.microsoft.com/en-us/library/58918ffs.aspx

1 Answer

1

You must read about reflection, but i will help you.

typeof(AudioListener).GetProperties(); You will get an array of propertyInfo on you can call its invoke method passing a instance of the class which you can create with Activator class.

Note: you can’t do
typeof(label).GetProperties() because you need to know the type before compile but you can do label.GetProperties();

A snippet to help you

    foreach (var prop in label.GetProperties())
    {
      Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(obj, null));
    }

// note obj is an instance of label's type

You can test for a single property:

PropertyInfo myPropInfo = label.GetProperty("MyProperty");

if (myPropInfo  == null)
{
throw new  DontPanicException();
}

before you ask to get the methods: MethodInfo methodInfo = label.GetMethod("MethodName"); methodInfo.Invoke(obj, parametersArray);

If it helped please vote up.

@Womrwood. Thanks for helping out. So reflection is what I need to read. Cheers.