Add component of unknown type

The following code does not work:

GameObject g = new GameObject("Player");
System.Type t = typeof(AutomatedPlayer);
 if (player_isAutomated)
        p = g.AddComponent(t);

AutomatedPlayer is a class I defined which inherits from MonoBehaviour.
Why is this not working?

Thank you

Like Hellium said in the comments above there’s no reason why AddComponent(typeof(YourClassName)) shouldn’t work when AddComponent<YourClassName>() works. That’s because the generic versions of AddComponent / GetComponent have been added just for convenience. Under the hood the generic version does just use the System.Type version anyways. And that’s not just in a metaphorical sense but literally.

So if it doesn’t work for you there has been other issues. Either your type can not be attached at all because it may not be compiled due to compiler errors or you haven’t saved the file so the content the compiler sees is not up to date. Another reason why it can’t be attached could be that you haven’t placed each of your MonoBehaviour derived types you wish to add to a gameobject in its own C# file where the file name matches the class name. This requirement still holds true.

The other option why “it doesn’t work”, as Hellium said, could be that your code doesn’t actually run because your if condition may not be true.

That’s why it’s important to be more specific what exactly doesn’t work and how you know that. So what have you done already to debug your issue? Another thing that isn’t clear is what’s the type of your variable “p”?

Keep in mind that AddComponent with a System.Type parameter has “Component” as return type. So without an explicit cast “p” could only be of type Component or UnityEngine.Object. Of course you could not access any class specific members with that variable. In order to access anything from a class you have to know its type or you have to know what interface(s) the class implements.