AudioSource does not play upon entering trigger
Ok, I have an item to collect. When you run into it, the item lights up in the UI, the item disappears, the score increases, and an audio clip is supposed to play. EVERYTHING works except the audio clip, so I know the trigger is working fine (no physics related issues).
My First Person Controller has the audio listener active. The item has the audio clip attached to it. The code on the item is listed below. If I click "Play On Awake" in the inspector, the clip will play when I start the game... so I know it's not a problem with the actual audio clip. It must be something in the code making it not play when I run into the trigger.
Thoughts? Thanks in advance!
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;
public class EggplantUI : MonoBehaviour
{
public int RotateSpeed;
public GameObject Eggplant;
public GameObject EggplantUIView;
public Score Score;
public AudioSource collectSound;
// Start is called before the first frame update
void Start()
{
collectSound = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
RotateSpeed = 2;
transform.Rotate(0, RotateSpeed, 0, Space.World);
}
void OnTriggerEnter ()
{
collectSound.Play();
Eggplant.SetActive(false);
EggplantUIView.SetActive(true);
Score.IncreaseScore(50);
}
}
Answer by tombedorchestra · Nov 25, 2020 at 11:27 PM
The problem was that the object was being set to false while the sound was playing. It never gave the item the chance to play the sound before being set inactive. I was able to get around this by setting it up in a coroutine. It's not the smoothest, but it works for my purpose.
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;
public class EggplantUI : MonoBehaviour
{
public int RotateSpeed;
public GameObject Eggplant;
public GameObject EggplantUIView;
public Score Score;
public AudioSource collectSound;
// Start is called before the first frame update
void Start()
{
collectSound = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
RotateSpeed = 2;
transform.Rotate(0, RotateSpeed, 0, Space.World);
}
IEnumerator ItemCollect()
{
collectSound.Play();
yield return new WaitForSeconds(0.6f);
Eggplant.SetActive(false);
EggplantUIView.SetActive(true);
Score.IncreaseScore(50);
}
void OnTriggerEnter ()
{
StartCoroutine (ItemCollect());
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613020536im_/https://answers.unity.com/themes/thub/images/avi.jpg)