Hi, I’m trying to use a bool that turns on an audiosource when it’s true, but it only seems to work when it’s false, or the wrong way round. I know this because I’ve set it to play when the bool is false in the code, but when it is set to true it plays instead.
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DGI : MonoBehaviour
{
public OPCBoolIn gasIn;
public AudioSource[] totalSirens;
private bool gasHazard;
// Update is called once per frame
void Update ()
{
Debug.Log(gasHazard);
gasHazard = gasIn.Get();
if (gasHazard)
{
Evacuate();
}
}
void Evacuate()
{
foreach (AudioSource srn in totalSirens)
{
if (!srn.isPlaying)
{
srn.Play();
}
else
{
srn.Stop();
}
}
}
}
If anybody could help, that’d be great!
Umm, you are basically switching on and off your siren…first time, it will be false, you launch it. Next update, gasHazard should still be true, this time isPlaying is true, so it will go to else and stop the play. Is this the intended behaviour?
Why do you have multiple copies of the same script, which ALL go through every siren? It feels like it would be more straightforward to either have one script per siren (that turns that specific siren on or off), or one script in the scene (that turns on or off all sirens).
Anyway, you’re stopping every siren instantly (as said in the previous answer). Basically your else statement should be in the part where you test for the gasHazard bool, not inside the Evacuate method. Try this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DGI : MonoBehaviour
{
public OPCBoolIn gasIn;
public AudioSource[] totalSirens;
private bool gasHazard;
// Update is called once per frame
void Update ()
{
Debug.Log(gasHazard);
gasHazard = gasIn.Get();
if (gasHazard)
{
Evacuate();
}
else //gasHazard has stopped, so stop sirens
{
StopEvacuate();
}
}
void Evacuate()
{
foreach (AudioSource srn in totalSirens)
{
if (!srn.isPlaying)
{
srn.Play();
}
}
}
void StopEvacuate()
{
foreach (AudioSource srn in totalSirens)
{
srn.Stop();
}
}
}