Return value of Type.GetType(string); null

Asked 1 years ago, Updated 1 years ago, 60 views

Type type=Type.GetType(typeof(Texture).FullName);

Unity returns null for the above C# script.

unity3d

2022-09-30 17:35

1 Answers

The following answer.unity3d has been answered.

http://answers.unity3d.com/questions/206665/typegettypestring-does-not-work-in-unity.html

It is recommended that the following wrappers be used:

public class WrapClass
{
        public static Type GetType (string typeName)
        {

                // Try Type.GetType() first.This will work with types defined
                // by the Monoruntime, in the same assembly as the caller, etc.
                var type = Type.GetType(typeName);

                // If it worked, then we're done here
                if(type!=null)
                        return type;

                // If the TypeName is a full name, then we can try loading the defining assembly directly
                if(typeName.Contains("."){

                        // Get the name of the assembly (Assumption is that we are using) 
                        // fully-qualified type names)
                        var assemblyName = typeName.Substring(0, typeName.IndexOf('.'));

                        // Attempt to load the indicated assembly
                        var assembly = Assembly.Load(assemblyName);
                        if(assembly==null)
                                return null;

                        // Ask that assembly to return the prop Type
                        type = assembly.GetType(typeName);
                        if(type!=null)
                                return type;

                }

                // If still haven't found the property type, we can enumerate all of the 
                // loaded assemblies and see if any of them define the type
                var currentAssembly=Assembly.GetExecutingAssembly();
                var referencedAssemblies=currentAssembly.GetReferencedAssemblies();
                foreach(variablyName in referencedAssemblies){

                        // Load the referenced assembly
                        var assembly = Assembly.Load(assemblyName);
                        if(assembly!=null){
                                // See if that assembly defines the named type
                                type = assembly.GetType(typeName);
                                if(type!=null)
                                        return type;
                        }
                }

                // The type just could not be found...
                return null;
        }
}

Unity5(beta) did not solve the problem.


2022-09-30 17:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.