Type.GetType can't support UnityEngine.UI.Image in unity5 ?

run script as below:
Debug.Log(“System.IO.File=” + Type.GetType(“System.IO.File”));
Debug.Log(“UnityEngine.Animation=” + Type.GetType(“UnityEngine.UI.Image”));
Debug.Log(“UnityEngine.Animation=” + Type.GetType(“UnityEngine.Animation”));

the result is:
System.IO.File is null=False
UnityEngine.UI.Image is null=True
UnityEngine.Animation is null=True

so I can’t use script:
Type t = Type.GetType(“UnityEngine.UI.Image”); gameObject.AddComponent(t);
to add component to a gameobject ,
and in unity5 the gameObject.AddComponent(“UnityEngine.UI.Image”) is not allowed;
the reflection mechanism can’t be used.
I wish allow gameObject.AddComponent(“UnityEngine.UI.Image”) method in unity 5.

This is not how to get what you want.

Do something more like this:

gameObject.AddComponent(new UnityEngine.UI.Image());

AddComponent takes an Object not a Type.

You should avoid reflection, it costs to much overhead and is not good for games.

I use lua script to add Image component.so must use gameObject.AddComponent(“UnityEngine.UI.Image”) method

wrong…

AddComponent most definately takes a System.Type as argument, it will create an instance of that type for you.

using UnityEngine.UI;
gameObject.AddComponent<Image>();
gameObject.AddComponent(typeof(Image));
gameObject.AddComponent("Image"); //obsolete in Unity5

Don’t really use AddComponent much, but I just finished making a custom UI component from an editor script and should have known that.

DAMN!! What was I thinking. hides in hole

1 Like