Script variables being reset after calling UnityEvent
On a two players game, I have a GameMaster object that keeps track of the player turn, which is an enum.
Depending on the current turn, the units of the player are selected or not when clicked. This triggers is a UnityEvent handled by the GameMaster (probably a bad name BTW, should be Board).
The problem I'm having is that the current turn has a default value (first player) when the UnityEvent triggers. Every time. It doesn't make any sense.
// GameMaster.cs
using UnityEngine;
public class GameMaster : MonoBehaviour
{
private PlayerTurn currentPlayerTurn;
void Start()
{
currentPlayerTurn = PlayerTurn.PlayerOne;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (currentPlayerTurn == PlayerTurn.PlayerOne)
{
currentPlayerTurn = PlayerTurn.PlayerTwo;
}
else
{
currentPlayerTurn = PlayerTurn.PlayerOne;
}
Debug.Log("New player turn: " + currentPlayerTurn);
}
}
public void onUnitClicked(Unit unit)
{
HandleUnitClicked(unit);
}
private void HandleUnitClicked(Unit unit)
{
Debug.Log("player turn: " + unit.PlayerTurn);
Debug.Log("current turn: " + currentPlayerTurn);
if (unit.PlayerTurn != currentPlayerTurn)
{
return;
}
// Here do the stuff for the selected unit
}
}
// Unit.cs
using UnityEngine;
using UnityEngine.Events;
[System.Serializable]
public class UnitClickedEvent : UnityEvent<Unit>
{
}
[System.Serializable]
public enum PlayerTurn
{
PlayerOne, PlayerTwo
}
public class Unit : MonoBehaviour
{
[SerializeField] private PlayerTurn playerTurn; // This is set to the correct value on the editor
[SerializeField] private UnitClickedEvent onClick;
public PlayerTurn PlayerTurn { get => playerTurn; }
void OnMouseDown()
{
onClick.Invoke(this);
}
}
The execution when clicking on a player two unit BEFORE switching turn prints:
player turn: PlayerTwo
current turn: PlayerOne
This is correct, as player one has de first turn
When switching turn by hitting the space bar, it prints:
New player turn: PlayerTwo
And when clicking on a player two unit again, it prints:
player turn: PlayerTwo
current turn: PlayerOne // -> This is incorrect!
So, basically, the currentTurn variable is always PlayerOne (default value) inside the event handler despite being set to the correct value
Just to clarify, if I print the value of currentTurn inside the Update method, it always has the correct value driven by the input (spacebar).
I had already this problem with another variable a few days ago. I removed that variable and actually improved the design, but not I'm having the same problem again.
Any ideas why this could be happening? It seems to me like anything invoked from UnityEvent is having the default variables values.
Answer by srodrigodev · May 30, 2020 at 02:50 PM
Still haven't managed to solve this or understand why it's happening.