- Home /
Check if a 2D Object Exists/or not; C#
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?
Does the else code run and you can't hear the audio or does the else code never run?
Is it possible that you are not actually destroying the ball if it leaves the screen? Or that you have not assigned an AudioClip?
I put in a Debug.Log message in the else code to test if it runs, and yes, it certainly does. I also confirmed that I have indeed assigned an AudioClip and that the ball is destroyed when it leaves the screen, as it comes in contact with a collider object that destroys it on contact. I'm led to believe this is some problem with audio.Play().
If the sound is currently 3D then the audiolistener might just might be too far from the audiosource. Try changing the sound to 2D. If you can hear it 2D then you can keep it 2D or change the audiosource settings so 3D sounds can be heard from further away.
Answer by KingGolem · May 31, 2015 at 11:45 AM
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.