I am making a Breakout clone as a learning experience, and I am trying to make the game play a failure sound when there are no balls left on screen. I created an empty game object to check if any of the three (possible) balls exist, and play the sound if they don’t. Here is the script I used:
using UnityEngine;
using System.Collections;
public class BallCounter : MonoBehaviour {
AudioSource audio;
Object ball1;
Object ball2;
Object ball3;
// Use this for initialization
void Start () {
audio = GetComponent<AudioSource> ();
}
// Update is called once per frame
void Update () {
ball1 = GameObject.Find ("Ball");
ball2 = GameObject.Find ("Ball 1");
ball3 = GameObject.Find ("Ball 2");
if (ball1 || ball2 || ball3) {
} else {
audio.Play ();
}
}
}
Sadly, it doesn’t work. What am I doing wrong?
Oh hey, I just solved it. The audio source works, but for some reason audio.Play() doesn’t want to work within an else statement. So I just made the else statement set a bool to true to trigger another if statement, in which I put audio.Play(). Here’s what I came up with:
using UnityEngine;
using System.Collections;
public class BallCounter : MonoBehaviour {
AudioSource audio;
public AudioClip FailureBuzz;
Object ball1;
Object ball2;
Object ball3;
bool playSound = false;
bool gameOver = false;
// Use this for initialization
void Start () {
audio = GetComponent<AudioSource> ();
}
// Update is called once per frame
void Update () {
ball1 = GameObject.Find ("Ball");
ball2 = GameObject.Find ("Ball 1");
ball3 = GameObject.Find ("Ball 2");
if (ball1 || ball2 || ball3) {
Debug.Log ("Balls exist");
} else {
playSound = true;
//audio.PlayOneShot (FailureBuzz);
Debug.Log ("Balls don't exist");
}
if ((playSound == true) && (gameOver == false)) {
audio.Play ();
gameOver = true;
}
}
}
It’s not exactly elegant, and I still have no idea why audio.Play() won’t run in an else statement, but this code works, and that’s all that matters. Thank you all for helping me debug.