Hi,
I’m trying to make an Othello game. My prefab contains an OthelloCell script, that manages the cell’s state, and and a CellColor script that manages the color of the cell according to the cell’s state.
If I add a breakpoint in “SetState”, I can see the event is invoked indeed.
However when I look in the inspector, the list of registered listeners to OnStateChanged is empty for all my cells. And thus my UpdateColor method is never called.
What am I doing wrong?
Here’s the code for my 2 classes
using UnityEngine;
using System.Collections;
using UnityEngine.Events;
public class OthelloCell : MonoBehaviour {
public enum CellState {Empty, White, Black};
public int currentState;
public UnityEvent OnStateChanged = new UnityEvent();
public void Start(){
SetState((int)CellState.Empty);
}
public void SetState(int state) {
if (currentState != state){
currentState = state;
if (OnStateChanged != null) {
OnStateChanged.Invoke();
}
}
}
}
using UnityEngine;
using System.Collections;
[RequireComponent (typeof(OthelloCell), typeof(Renderer))]
public class CellColor : MonoBehaviour {
public Color emptyCellColor;
public Color blackCellColor;
public Color whiteCellColor;
private OthelloCell othelloCell;
private Renderer myRenderer;
// Use this for initialization
void Start () {
othelloCell = GetComponent<OthelloCell> ();
myRenderer = GetComponent<Renderer> ();
othelloCell.OnStateChanged.AddListener (UpdateColor);
}
void UpdateColor(){
switch (othelloCell.currentState){
case (int)OthelloCell.CellState.Black:
myRenderer.material.color = blackCellColor;
break;
case (int)OthelloCell.CellState.White:
myRenderer.material.color = whiteCellColor;
break;
default:
myRenderer.material.color = emptyCellColor;
break;
}
}
}