Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

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

Discussion in 'Scripting' started by alexhy, Apr 28, 2015.

  1. alexhy

    alexhy

    Joined:
    Nov 21, 2013
    Posts:
    26
    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.
     
  2. Chris-Trueman

    Chris-Trueman

    Joined:
    Oct 10, 2014
    Posts:
    1,256
    This is not how to get what you want.

    Do something more like this:
    Code (CSharp):
    1. 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.
     
  3. alexhy

    alexhy

    Joined:
    Nov 21, 2013
    Posts:
    26
    I use lua script to add Image component.so must use gameObject.AddComponent("UnityEngine.UI.Image") method
     
  4. dterbeest

    dterbeest

    Joined:
    Mar 23, 2012
    Posts:
    389
    wrong..

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

    Code (csharp):
    1. using UnityEngine.UI;
    2. gameObject.AddComponent<Image>();
    3. gameObject.AddComponent(typeof(Image));
    4. gameObject.AddComponent("Image"); //obsolete in Unity5
     
  5. Chris-Trueman

    Chris-Trueman

    Joined:
    Oct 10, 2014
    Posts:
    1,256
    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*
     
    dterbeest likes this.