I am trying to set up a script that turns off audio listeners depending on the game’s state. To do this I have my function subscribed to an event.
public class ActivatePlayerAudioListener : MonoBehaviour
{
[SerializeField]
AudioListener listener;
Directory directory;
Transform player;
Transform rootTransform;
GameFlow gameFlow;
bool startTriggered;
bool amInBattle = false;
// Start is called before the first frame update
private void OnEnable()
{
if (startTriggered == true)
{
gameFlow = Directory.GetDirectory().GetGameFlow();
//Debug.Log("Game Flow : " + gameFlow.name);
gameFlow.GameStateChangeEvent += CheckMode;
}
}
private void OnDisable()
{
if (gameFlow == null)
{
return;
}
gameFlow.GameStateChangeEvent -= CheckMode;
}
void Start()
{
gameFlow = Directory.GetDirectory().GetGameFlow();
//Debug.Log("Game Flow : " + gameFlow.name);
gameFlow.GameStateChangeEvent += CheckMode;
startTriggered = true;
}
// Update is called once per frame
void CheckMode(object sender, GameFlow.GameStateEventArgs eventArgs)
{
GameFlow.GameState state = eventArgs.currentGameState;
Debug.Log("Activate Audio Listener Checking Game Mode... " + state);
if (state == GameFlow.GameState.Battle)
{
SetInBattleState(true);
return;
}
else
{
SetInBattleState(false);
return;
}
}
private void SetInBattleState(bool state)
{
Debug.Log("Setting In Battle " + state);
amInBattle = state;
}
void Update()
{
listener.enabled = false;
Debug.Log("amInBattle is " + amInBattle);
if (!amInBattle)
{
return;
}
//Debug.Log("Audio listener in battle...");
directory = Directory.GetDirectory();
rootTransform = this.transform.root;
player = directory.GetBattlefieldInfo().GetPlayerTransform();
// Debug.Log("PLAYER POS: " + player.position);
if (player == rootTransform)
{
//Debug.Log("AM PLAYER");
listener.enabled = true;
}
}
}
The bool “amInBattle” is private. Nothing outside of “CheckMode()” should have the ability to set “amInBattle.” I can tell from my debug logs that when I enter battle, “amInBattle” does get set to true. Therefore, all my code does atm is switch all the audio listeners off. However, the debug log in the update function never reads “amInBattle” as true. Is there something I am missing about how events, and our booleans work?