- Home /
Is it bad practice to put a custom Editor class in the same file as the Monobehaviour it affects?
So the documentation says to put your Editor scripts into an Editor folder to stop them compiling at runtime.
However, if I place the MonoBehaviour and Editor classes into a single file with the name of the MonoBehaviour for the file name, it seems to work anyway (and not when in an Editor folder). This reduces clutter for small scripts that you want to give custom inspectors, but is it bad practice?
using UnityEngine;
using UnityEditor;
public class Example : MonoBehaviour {
// Stuff here
}
[CustomEditor(typeof(Example))]
public class ExampleEditor : Editor {
// Stuff here
}
That shouldn't work unless the whole file is in the Editor folder, in which case it won't be included in your built game...
The file isn't in an Editor folder, but its Editor part does work.
If you don't want to break out your editor class or editor code into a separate script, you can also use preprocessor directives to control what gets compiled into your game. In your case, wrapping the custom editor class in
#if UNITY_EDITOR
//editor Code goes here
#endif
Would prevent your editor code from compiling into the build of your game.
I was thinking the same as achynes. I find more confortable to add the custom editor on the same file.
Anybody know if it has some disadvantages?
Answer by PedroFabri · Sep 09, 2020 at 01:33 PM
(A bit late, but was searching the same thing and would like to help someone here)
In my opinion, as long as it's not too complex, it's not a bad practice. But if your editor is a really big file, things can get messy.
JUST REMEMBER: If you put your Editor script inside the same file, remember to check if you're in the editor first. Otherwise your game will not build, because de UnityEditor namespace is not added in builds.
Just do something like this:
// Import your regular stuff
using UnityEngine;
using UnityEngine.SceneManagement;
// using blábláblá
// Only import UnityEditor if we're in the editor.
#if UNITY_EDITOR
using UnityEditor;
#endif
public class MyClass : MonoBehaviour
{
// Cool stuff here
}
// Again, class will be declared only if we're in the editor.
#if UNITY_EDITOR
[CustomEditor(typeof(MyClass))]
public class MyClassEditor : Editor
{
// Cool editor stuff here
}
#endif
Sad to answer a 4 y.o. question, but hope it helps someone!