Home > Net >  C# preprocessor warning if will cause compile error
C# preprocessor warning if will cause compile error

Time:07-26

I'm using unity I want to wrap my class in a #if UNITY_EDITOR. I can still access that class from other scripts without the if statement causing errors and no warning to other programmers until build compilation.

Example:

#if UNITY_EDITOR
using UnityEditor
public class ObservableEditor : Editor
{
    //Code here
}
#endif
public class AnotherClass
{
   public AnotherClass()
   {
        //Call ObservableEditor Observables
        //causes error if not in unity editor programmer is unaware until build
   }
}

Is there a good way to throw a warning to other programmers so they know to use the preprocessor?

CodePudding user response:

As far as I know, there is no easy way to issue a warning for when this happens, but C# does have a very neat attribute that may a accomplish what you want. The Conditional attribute makes so the class/method is only compiled when the provided pre-processor is defined, but if the class/method is called somewhere else it won't throw any errors, even it the pre-processor is not defined

I think that if you use it like this it will work:

 using UnityEditor
    
 [System.Diagnostics.Conditional("UNITY_EDITOR")]
 public class ObservableEditor : Editor
 {
     //Code here
 }

The only problem is that the programmer will still be unaware that the class/method is only present in the editor, but there are other ways to communicate that, like putting the class in an editor namespace and in an editor assembly definition so that unity will give an error even while in the editor

  • Related