Skip to content

Instantly share code, notes, and snippets.

@tsubaki
Last active October 9, 2019 02:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsubaki/9427141 to your computer and use it in GitHub Desktop.
Save tsubaki/9427141 to your computer and use it in GitHub Desktop.
値の変更を通知するオブジェクト。基本型のみ可能っぽい。要4.5
using UnityEngine;
using System.Collections;
using System;
[System.Serializable]
public class NotificationObject<T>
{
public delegate void NotificationAction (T t);
private T data;
public NotificationObject (T t)
{
Value = t;
}
public NotificationObject ()
{
}
~NotificationObject ()
{
Dispose ();
}
public UnityEngine.Events.UnityAction<T> action;
public T Value {
get {
return data;
}
set {
data = value;
Notice ();
}
}
private void Notice ()
{
if (action != null)
action (data);
}
public void Dispose ()
{
action = null;
}
}
@tsubaki
Copy link
Author

tsubaki commented Mar 8, 2014

下のように記述しておくと、値(Value)を変更した度にUpdateScoreLabelを呼び出す。

NotificationObject<int> score = new NotificationObject<int>(0);

void Start(){
    score.action += UpdateScoreLabel;
}
void UpdateScoreLabel(int score){
    Debug.Log(score);
}

自身が破棄されるタイミングで下の処理で後片付けをしておくと吉。

score.action -= UpdateScoreLabel;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment