Search code examples
c#reflectioninterfacenullcreateinstance

Activator.CreateInstance(Type T) returns null


EDIT: This code runs as a custom inspector code in unity, but I am not sure if it is relevant, if it is, I will post the entire class.

I want to get all classes that implements a specific interface, and show an options list so a user can choose how to implement the interface.

It is a simple interface that describes the character behavior.

I have tried to replace the Interface with an abstract class, but for no avail...

In the debug I can see, that the returned values is null.

All I have found online says that the type might not exist, but it is impossible in my case, because I get my type using reflection.

ICombatBehaviour combat;
private string[] FindAllCombatOptions(out List<Type> existingTypes)
{
    List<string> options = new List<string>();
    existingTypes = new List<Type>();
    var combatBehaviours = Assembly.GetAssembly(typeof(ICombatBehaviour)).GetTypes()
        .Where(myType => myType.IsClass && !myType.IsAbstract && typeof(ICombatBehaviour).IsAssignableFrom(myType));
    foreach (var behaviour in combatBehaviours)
    {
        existingTypes.Add(behaviour);
        options.Add(behaviour.Name);
    }
    return options.ToArray();
}
private void UpdateType(List<Type> types)
{
    combat = Activator.CreateInstance(types[index]) as ICombatBehaviour;
}

The UpdateType() method, gets all the types that FindAllCombatOptions() method has found, and takes the type in the selected index. The type is correct, but the combat variable remains null...

The ICombatBehavior:

public interface ICombatBehaviour
{

}

The Implementing classes:

public class FightBehaviour : ICombatBehaviour
{

}

public class EscapeBehaviour : ICombatBehaviour
{

}

This is the calling function:

public override void SelectType()
    {
        List<Type> types;
        string[] options = FindAllCombatOptions(out types);
        index = AskUserForAType(options); // Currently returns only zero
        UpdateType(types);
    }

Solution

  • The solution was pretty simple. The problem was not in the code, but in Unity3D.

    Unity created the classes FightBehaviour and EscapeBehaviour as a MonoBehaviour class, which can not be instantiated. Therefore I needed to set it to a normal class.

    Thanks for everyone in the comments that helped me, I really appreciate it.