Created
December 21, 2022 03:25
-
-
Save cathei/e904d00d522e6dcca6708127cc2bcb9d to your computer and use it in GitHub Desktop.
Sample of using reactive model instead of direct references
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
public class PlayerModel | |
{ | |
public ReactiveProperty<int> Score { get; } = new(); | |
} | |
public class GameModel | |
{ | |
public ReactiveCollection<PlayerModel> Players { get; } = new(); | |
} | |
// PlayerSpawner would be the one that placed in Scene | |
public class PlayerSpawner : MonoBehaviour | |
{ | |
// Injected from somewhere | |
public GameModel Model { get; set; } | |
[SerializeField] private Player playerPrefab; | |
[SerializeField] private ScoreUI scoreUIPrefab; | |
public void Start() | |
{ | |
// You'd also manage unsubscribing in real game | |
Model.Players.OnAdded += SpawnPlayer; | |
} | |
private void SpawnPlayer(PlayerModel playerModel) | |
{ | |
var player = Instantiate(playerPrefab); | |
// inject to an instantiated object | |
player.Model = playerModel; | |
var scoreUI = Instantiate(scoreUIPrefab); | |
// inject to an instantiated object | |
scoreUI.Model = playerModel; | |
} | |
} | |
public class Player : MonoBehaviour | |
{ | |
public PlayerModel Model { get; set; } | |
public void ScoreGain() | |
{ | |
Model.Score.Value += 1; | |
} | |
} | |
public class ScoreUI : MonoBehaviour | |
{ | |
public PlayerModel Model { get; set; } | |
[SerializeField] private Text scoreText; | |
private void Start() | |
{ | |
// You'd also manage unsubscribing in real game | |
Model.Score.OnChanged += UpdateScore; | |
} | |
private void UpdateScore(int score) | |
{ | |
scoreText.text = score.ToString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment