Skip to content

Instantly share code, notes, and snippets.

@CSaratakij
Created June 8, 2025 19:45
Show Gist options
  • Save CSaratakij/2688dbe2f5441e160a6c783d56614164 to your computer and use it in GitHub Desktop.
Save CSaratakij/2688dbe2f5441e160a6c783d56614164 to your computer and use it in GitHub Desktop.
Unity, simple one way value binding example
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