- Home /
Question by
SalihSahin08 · Aug 22, 2020 at 02:41 PM ·
scripting problemuigameobjectaudiocanvas
Ingame music goes on but it should stop when you die (DeathCanvas Activate) or win (LevelComplete Canvas Activates)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundManager : MonoBehaviour
{
public GameObject BackgroundSound;
public GameObject GameManager;
public GameObject LevelComplete;
public GameObject DeathCanvas;
public float sec = 1.5f;
void Start()
{
BackgroundSound.GetComponent<AudioSource>().enabled = false;
StartCoroutine(LateCall());
}
IEnumerator LateCall()
{
yield return new WaitForSeconds(sec);
BackgroundSound.GetComponent<AudioSource>().enabled = true;
if (LevelComplete.activeSelf || DeathCanvas.activeSelf == true) //ingame music should go off if you lose or win the level
{
BackgroundSound.GetComponent<AudioSource>().enabled = false;
} else
{
BackgroundSound.GetComponent<AudioSource>().enabled = true;
}
}
}
Comment
Answer by highpockets · Aug 22, 2020 at 10:54 PM
It looks like you are just calling the LateCall function once from the Start method of the object this script is on, unless you call it somewhere else in code you’re not supplying here.
From LevelComplete and DeathCanvas you should maybe fire an event from a script inside an OnEnable or Start function and add a listener to that event in the script you posted. So first you could create an event:
using UnityEngine;
using UnityEngine.Events;
public class MyEventSystem : MonoBehaviour
{
public UnityEvent turnOffAudioEvent;
private void Awake()
{
if(turnOffAudioEvent == null)
turnOffAudioEvent = new UnityEvent();
}
public void FireUnityEvent(UnityEvent _event)
{
if(_event != null)
_event.Invoke();
}
}
Then you could fire the event from the respective GameObjects:
using UnityEngine;
public class StopAudioNotifier : MonoBehaviour
{
[SerializeField] private MyEventSystem events;
private void Start()
{
events.FireUnityEvent( events.turnOffAudioEvent );
}
}
Now add a listener:
public class SoundManager : MonoBehaviour
{
public GameObject BackgroundSound;
public GameObject GameManager;
public GameObject LevelComplete;
public GameObject DeathCanvas;
public MyEventSystem events;
public float sec = 1.5f;
void Start()
{
events.turnOffAudioEvent.AddListener( () =>
{
BackgroundSound.GetComponent<AudioSource>().enabled = false;
});
BackgroundSound.GetComponent<AudioSource>().enabled = false;
StartCoroutine(LateCall());
}
IEnumerator LateCall()
{
yield return new WaitForSeconds(sec);
BackgroundSound.GetComponent<AudioSource>().enabled = true;
}
}
Hope that helps