Saturday, January 30, 2016

Observer Pattern in Unity3D's C#

Can't tell you how often I use observers, and delegates and events in C# when using Unity3D. Say you have a boolean value called isWinner in your Game Class. If you want to see if that bool value has became true in a different class you need to subscribe using an observer and observable. Since isWinner is boolean, a different class called Leaderboards needs to run a method that increments a GameCenter leaderboard. You accomplish this through the Observer Pattern and Delegates.

In a Game class:

private static bool _isWinner = false;
public static bool isWinner {
get { return _isWinner; }
set { _isWinner = value;
if (_isWinner) {
initiateWinner();
}
}
}

public delegate void Winner();
public static event Winner initiateWinner;

        public static void finishGame() {
                 isWinner = true;
        }

In a Leaderboard class:

void OnEnable() {
Game.initiateWinner += doWin;
}

void OnDisable() {
Game.initiateWinner -= doWin;
}

void doWin() {
                // do your gamecenter, social, prime31 code here
}


From above it's easy to assess that is happening. isWinner is changed, and the event initateWinner() is initiated. Then on the Leaderboard class it's observed and calls doWin();.

No comments:

Post a Comment