A [possible] solution to those annoying UnityEditor namespace compiler issues

I got incredibly annoyed with Unity today…

I was working on my developer tool project and in the process of creating a Web player demo, I got that annoying build error message because some of the code in my project has some UnityEditor code in it. I know it’s not supposed to be buildable, but that’s not a problem for me, because those scripts are not suppose to go into anyone’s final game code anyway.

“Just move it into the Editor folder,” some of you may say. Based on what I’m doing, things are just not that simple. That just creates more problems. And the other workarounds are just horrible.

So I decided to write an editor script to deal with this issue once and for all. I call it “CompileSafe”

Here’s what it does…

It takes code written like this:

using UnityEngine;
using System.Collections;
//#nocompile
using UnityEditor;
//#compile

public class TestFile : MonoBehaviour {

	// Use this for initialization
	void Start () {
	}
	
	// Update is called once per frame
	void Update () {
	}
	
	void SaveAssets() {
//#nocompile
		AssetDatabase.SaveAssets();
		AssetDatabase.Refresh();	
//#compile
	}
}

Backs the file up to a txt file, which Unity ignores. And converts the file into this:

using UnityEngine;
using System.Collections;
//#nocompile
//using UnityEditor;
//#compile

public class TestFile : MonoBehaviour {

	// Use this for initialization
	void Start () {
	}
	
	// Update is called once per frame
	void Update () {
	}
	
	void SaveAssets() {
//#nocompile
//		AssetDatabase.SaveAssets();
//		AssetDatabase.Refresh();	
//#compile
	}
}

Do you see what it does? Problem solved. To put things back the way they were, it just deletes the commented file and renames the original.

Code written to do this needs to be flawless and check every little thing, because if there are any mistakes in it, your project source code could be completely trashed. And if you’re not backing up your files multiple times a day like I do, it can be a complete nightmare.

Any comments or suggests? Are you doing something similar?

… and no, I’m not posting the code. Too much of a liability. :wink:

I’m probably missing something from what you needed, but just curious: why couldn’t you use UNITY_EDITOR preprocessor define?

Ha ha! Nice.Thank you.

I was the one missing something. Never saw this page before and all the forum/answers responses that I read said you have to move the script to a EDITOR folder (which means other classes can’t see it) and that you can’t mix UnityEditor code in with your regular code.

I learn something new about Unity every day. :sunglasses: