Audio plays on awake with "play on awake" unchecked
Hi, I want my sound to play on the win condition. Currently it plays at the begininng of the game and the win condition though. The "play on awake" is unchecked. I have tried removing the audio component and redoing it. I have tried removing the audio clip from the game and reimporting it. Nothing has worked. Here is my script:
using UnityEngine; using System.Collections; using UnityEngine.UI;
//[RequireComponent(typeof(AudioSource))] public class PlayerController : MonoBehaviour {
//all public show up in the inspector
public float speed;
public Text countText;
public Text winText;
//public AudioClip winSound;
private Rigidbody rb;
private int count;
private GameObject[] getCount;
private int numPickUp;
private AudioSource sound;
//Update is called before rendering a frame--for most game code
//FixedUpdate is called before performing physics calculations-physics goes here
//Start is called on the first frame that the script is active, generally first of the game
void Start()
{
rb = GetComponent<Rigidbody> ();
count = 0;
SetCountText ();
winText.text = "";
getCount = GameObject.FindGameObjectsWithTag ("Pick Up");
numPickUp = getCount.Length;
}
void FixedUpdate()
{
//floats store inputs from the getaxis functions controlled by the keyboard
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0, moveVertical);
rb.AddForce (movement * speed);
}
void OnTriggerEnter (Collider other)
{
if (other.gameObject.CompareTag ("Pick Up"))
{
count += 1;
other.gameObject.SetActive (false);
SetCountText ();
}
}
void SetCountText ()
{
countText.text = "Count: " + count.ToString () ;
if (count >= numPickUp)
{
winText.text = "You Win!" ;
sound = GetComponent<AudioSource>();
sound.Play();
//source = GetComponent<AudioSource> ();
//source.Play ();
//source.PlayOneShot (winSound);
}
}
}
Answer by Chubzdoomer · Feb 13, 2017 at 02:59 PM
It looks like SetCountText is running before numPickUp is initialized, which results in "if (count >= numPickUp)" immediately evaluating to true.
Try rearranging your code so that both "getCount = GameObject.FindGameObjectsWithTag ("Pick Up");" and "numPickUp = getCount.Length;" come before "SetCountText()" in your Start function. That should do the trick!
Your answer
![](https://koobas.hobune.stream/wayback/20220612110845im_/https://answers.unity.com/themes/thub/images/avi.jpg)