Created
March 17, 2021 12:35
-
-
Save Ryxali/e71d4c7a2e7ec000cde87551c15cd113 to your computer and use it in GitHub Desktop.
Theorizing a way to expose values serialized on unity objects to internal classes without memory fragmentation at runtime and minimizing dependencies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// For consumers of config fields | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
public struct ConfigValue<T> { | |
public T Value | |
#if UNITY_EDITOR | |
=> field.Value; | |
#else | |
{ get; } | |
#endif | |
#if UNITY_EDITOR | |
private ConfigField<T> field; | |
#endif | |
public ConfigValue(ConfigField<T> configField) | |
{ | |
#if UNITY_EDITOR | |
field = configField; | |
#else | |
Value = configField.Value; | |
#endif | |
} | |
} | |
/// <summary> | |
/// Allows you to serialize a value as a config field. | |
/// Consider adding an inspector editor to give it a nicer look | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
[System.Serializable] | |
public class ConfigField<T> { | |
public T Value => value; | |
[SerializeField] | |
protected T value; | |
public ConfigField() | |
{ | |
} | |
private ConfigField(T value) { | |
this.value = value; | |
} | |
public static implicit operator ConfigField<T>(T value) { | |
return new ConfigField<T>(value); | |
} | |
} | |
// concrete classes needed due to | |
public class ConfigFieldInt : ConfigField<int> | |
{ | |
public static implicit operator ConfigFieldInt(int value) | |
{ | |
return new ConfigFieldInt { value = value }; | |
} | |
} | |
/// <summary> | |
/// Serializes as any class | |
/// </summary> | |
public class ExampleBehaviour : MonoBehaviour { | |
public ConfigFieldInt exampleField = 32; | |
} | |
/// <summary> | |
/// In this example, the ConfigValue will be flexible to inspector editing in editor, | |
/// and fast without memory fragmentation in release | |
/// </summary> | |
public class ExampleConsumer { | |
public ConfigValue<int> setting; | |
public ExampleConsumer(ConfigField<int> setting) | |
{ | |
this.setting = new ConfigValue<int>(setting); | |
} | |
public int Foo(int value) | |
{ | |
return value + setting.Value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment