Check if a class is already in the project

I would like to know if I can check if some class is in the project, if it’s true, I derive my class from this. For example:

Supose I need derive my class ClassB from ClassA. But I need first, check if there is ClassA in the project, in case of no, I would derive from MonoBehaviour. Something like this:

#if (ClassA is in the project)
public class ClassB : ClassA
#else
public class ClassB : MonoBehaviour
#endif

That’s kind of a problem because if you test for a class not in the project, it will throw an error and not compile.

if(typeof(className) != null){
//do something
}

It will compile if the class exists, but not if it doesn’t.

Unfortunately your class needs to be defined at compile-time, and I don’t think there is a way in Unity to check if a class exists using compile-time if checks (#if).

You CAN check if a class exists at runtime using reflection:

bool classAExists = (null != Type.GetType("ClassA"));

But you cannot use a runtime “if” check like this to decide the parent class of another class, because the classes must be defined at compile time.

1 Like

Are you really sure? Because I’ve alteady seen a script that check if Multiplayer is enabled to change if class derive from MonoBehaviour or NetworkBehaviour using #if and #endif

Because of that, I think that it’s possible somehow. But, anyway, thank you for the reply and suggestions.

Note, OP wants to do this as a compiler time directive. Not at runtime. Since they want to define what class something derives from.

In which case… no, there is no way to check if a specific type exists in a compiler directive.

Instead you check if a SYMBOL exists. In the case of the Multiplayer, there is probably a Multiplayer symbol that the script looks for being defined somewhere in the project.

What you can do is whatever class it is you’re testing for… if say it comes from a UnityPackage, or from a dll, or whatever. When it gets included into your project, you also define the symbol for the compiler directive.

Here is a list of existing symbols, and it contains how you can include custom symbols as an RSP file:

You can also define them through the Player Settings.

2 Likes

Much like @lordofduct said, the symbols must be defined in Unity for them to exist in the script. Unlike usual C#, you cannot “#define” symbols in scripts. If you want to add a symbol, you can add it in Unity’s PlayerSettings-> Other → Scripting Define Symbols (Platform custom define symbols). You can also create a .rsp file in your Assets folder to add scripting define symbols (Global custom define symbols).

You cannot have those scripting define symbols automatically tell you if a class exists.

More info here, search for Platform custom #defines and Global custom #defines:
https://docs.unity3d.com/Manual/PlatformDependentCompilation.html