Type.GetType(string) does not work in Unity

Calling:

Type type = Type.GetType("MyType");
Debug.Log("typeIsNull = " + (type == null));

Will result in “typeIsNull = true”, and yes the public class MyType exists in my unity project.

How do I fix this?

I also encountered this issue while working on some custom Asset Editor code that needs to serialize and deserialize Asset data, and discovered that Type.GetType() will return the expected Type for some types, like those defined in the Mono Runtime, while returning NULL for those defined in UnityEngine (for instance).

Because of this, I decided to create a wrapper function that seems to work for all of the types I’ve tried it on so far:

public static Type GetType( string TypeName )
{

	// Try Type.GetType() first. This will work with types defined
	// by the Mono runtime, 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 proper Type
		type = assembly.GetType( TypeName );
		if( type != null )
			return type;

	}

	// If we still haven't found the proper 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( var assemblyName 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 couldn't be found...
	return null;

}

I hope this is helpful to someone.

In java you would use the method Class.forName().

So... I googled c# class.forname equivalent and found this:

http://msdn.microsoft.com/en-us/library/aa310400%28v=vs.71%29.aspx

Hope it helps.