Preprocessor conditional code for cleaner inspector options
I started learning Unity this past weekend, and I'm having similar problems with preprocessor conditionals. I want to clear up clutter in the inspector by only providing declarations and access only to relevant variables. That way, I can increase the re-usability of my scripts while avoiding huge if statements. The following code returns a "Invalid preprocessor directive" and a "Single-line comment or end-of-line expected" on the lines following the #if and #elif directives. using UnityEngine; using System.Collections;
public class GunController : MonoBehaviour
{
public enum GunType { None, Projectile, Laser, Plasma }; // Behavior labels
public GunType type = GunType.Laser; // Selectable via drop-down menu
#if (type == GunType.Laser)
float power = 0; // Not relevant for a mass driver
#elif (type == GunType.Projectile)
float velocity = 0; // Not relevant for a laser
#else
// Other conditions follow
#endif
}
Is it not possible to use directives within a class? Am I asking for too much? My alternative is just to make separate classes for each type of weapon. Also, is this even the right approach? This would only work if the scripts are compiled on a per-use basis, which I don't understand if they are or not. Do you have alternatives?
Answer by laurentlavigne · Dec 19, 2015 at 10:38 AM
I thought that U5 introduced an attribute [ShowIf(bolean)] that does what you're looking for but I cannot find it. Until it magically re-appears, the official solution is this: http://docs.unity3d.com/Manual/editor-PropertyDrawers.html
Your answer
Follow this Question
Related Questions
Why does rotating via viewport give different values than inspector rotations? 2 Answers
How do I get a List or array in a custom inspector? 1 Answer
Multiply script of same type in single game object, how to choose in inspector 0 Answers
How to drag a specific component reference from one object's Inspector view to another one? 1 Answer
Inspector Euler angles deviates from Euler angles in code 1 Answer