Created
June 8, 2025 19:45
-
-
Save CSaratakij/2688dbe2f5441e160a6c783d56614164 to your computer and use it in GitHub Desktop.
Unity, simple one way value binding example
This file contains hidden or 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
using System; | |
using UnityEngine; | |
// Note : simple one way value binding example | |
public class TestReactive : MonoBehaviour | |
{ | |
public string Message | |
{ | |
get => message; | |
set => SetWithNotify(ref message, value, nameof(Message), OnValueChanged); | |
} | |
public int Number | |
{ | |
get => number; | |
set => SetWithNotify(ref number, value, nameof(Number), OnValueChanged); | |
} | |
private string message = "This is default message"; | |
private int number = 0; | |
// Note : react on start (default value) | |
private void Start() | |
{ | |
OnValueChanged(nameof(Message)); | |
OnValueChanged(nameof(Number)); | |
} | |
// Note : react on press 'Space' key | |
private void Update() | |
{ | |
if (Input.GetKeyDown(KeyCode.Space)) | |
{ | |
Message = $"Pressed at in-game time : {Time.time}"; | |
Number += 1; | |
} | |
} | |
private void SetWithNotify<T>(ref T field, T value, string propertyName, Action<string> onValueChanged = null, bool checkChanged = true) | |
{ | |
bool isValid = (checkChanged) ? !Equals(field, value) : true; | |
if (isValid) | |
{ | |
field = value; | |
onValueChanged?.Invoke(propertyName); | |
} | |
} | |
private void OnValueChanged(string propertyName) | |
{ | |
switch (propertyName) | |
{ | |
case nameof(Message): | |
{ | |
Debug.Log(Message); | |
} | |
break; | |
case nameof(Number): | |
{ | |
Debug.Log(Number); | |
} | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment