- Home /
How should I make this Audio play?
I was trying to make win and lose audios for my new game, and these audio will not play on the game over, only when I hit OnAwake to test. I have a bad game over and a good game over script. Please help me- it's my first game.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameOver : MonoBehaviour
{
public GameObject GameOverPanel;
public AudioSource audioSource;
public AudioSource bgmusic;
// Update is called once per frame
void Update()
{
if(GameObject.FindGameObjectWithTag("Player") == null)
{
GameOverPanel.SetActive(true);
bgmusic.Stop();
audioSource.Play();
}
}
public void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class WinManager : MonoBehaviour
{
// defines
public GameObject GameOverPanel;
public GameObject Image;
public Text GameOverText;
public Sprite Goodending;
public float score = 5;
public Sprite badending;
public AudioSource win;
public AudioSource bgmusic;
// Update is called once per frame
void Update()
{
if(GameObject.FindGameObjectWithTag("Player") != null)
{
score -= 1 * Time.deltaTime;
}
//condition for win, in this case running out the timer
if(score < -5)
{
//win text
GameOverText.text = "You Win! You got to school on time. P.S. I'm making more features later, so there's not much yet.";
GameOverText.fontSize = 40;
Image.GetComponent<Image>().sprite = Goodending;
GameOverPanel.SetActive(true);
bgmusic.Stop();
win.Play();
}
else
{
GameOverText.text = "Game Over! You got a ticket and totaled your car.";
GameOverText.fontSize = 65;
Image.GetComponent<Image>().sprite = badending;
}
}
}
Answer by makled · May 12 at 09:53 AM
Hey,
There is so much to unpack here.
I'll first start by asking you if this code is in 1 single script or 2 separate scripts. If it is in 1 single script I would separate them into two different scripts.
Next thing, and this is the major problem is that you have to avoid using "FindObject" in Update methods. This is very expensive and is not best practice for your game. You could always have a reference to the Player on start and keep it. You don't need to check if the player is there every frame.
Regarding the sound, I need more information to pin point the problem. Which object is the audio source connected to?
What exactly happens to the player if you lose or win? Does it get destroyed? If it gets destroyed, do you have your audio sources on the player?