I need to group all my constants into one file and show them on the inspector. Here’s what i’ve tried:
-
#defineconstants#define speed 10.0f #define hp 3This doesn’t work, no matter where i put them, Error:
Cannot define or undefine preprocessor symbols after first token in file
-
Use static
public static readonly float speed = 10.0f; public static readonly int hp = 3;It works, but when i attach it to the main camera, the constants do not show up in the inspector window. Well now I know inspector doesn’t support static field.
-
Use Singleton as suggested
using UnityEngine; using System.Collections; public class GameConfig : MonoBehaviour { private static GameConfig instance; public GameConfig() { if (instance != null) { Debug.LogError("GameConfig Warning: unable to create multiple instances"); } instance = this; } public static GameConfig Instance { get { if (instance == null) { Debug.Log("GameConfig: Creating an instance"); new GameConfig(); } return instance; } }Now if I add:
public float speed = 10.0f;the GameConfig.Instance.speed IS accessible, but the mono editor does not pop out auto completion. And it get this message:
CompareBaseObjects can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don’t use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.If I try:
public float speed = 10.0f; public float Speed {get {return speed;}}I get the same message.
But the game can still work, and variables show on inspector correctly.
Note: Even if i fix it, is there any other ways to do? since it seems redundant to write a constants with 2 names (property + field) and tedious work.
To use singleton in a gameObject in Unity by C#, you should not use the constructor of sub class(GameConfig), but create a GameObject and then add the needed component to it. Like this:
By the way, in your method-2, you can get things done by setting up an inspect UI by your self. Build up a custom editor for GameConfig and the add things you want to inspect. Refer to CustomEditor attribute and Editor.OnInspectorGUI for more information. If you don’t know how to customize an inspector or how to extend the default editor, you can find some useful guides in the Extending Editor in Unity’s site (Custom Inspectors section may be suit for you).