- Home /
Cannot get trigger sound to play for collectibles
I cannot get the sound to play for collectibles made from the following script:
public class SpawnerManager : MonoBehaviour { public GameObject prefab; public int numberOfObjects; public float radius; public float heightTimesRadius;
void Start()
{
for (int i = 0; i < numberOfObjects; i++)
{
float angle = i * Mathf.PI * 2 / numberOfObjects;
Vector3 pos = new Vector3(Mathf.Cos(angle), heightTimesRadius, Mathf.Sin(angle)) * radius;
Instantiate(prefab, pos, Quaternion.identity);
}
}
This is my audio script, which I add as a component to my object along with the script above:
public class Collectable : MonoBehaviour {
void OnTriggerEnter()
{
AudioSource source = GetComponent<AudioSource> ();
source.Play ();
}
}
I can use the 2nd script to make a random object I create trigger the sound on collision, but I cannot get the spawned objects from my first script to trigger any sound. Advice?
EDIT It seems that the trigger is set to the coordinates in the center of the circle created rather than for each individual collectible that makes up the circle. Additionally, a sound plays immediately as I start the game (since I'm placed in the center of the circle of collectibles) despite having "play on awake" turned off in the audio source component.
Answer by unidad2pete · Aug 19, 2017 at 01:11 AM
Maybe next questions are obvious for you, but most problems are obvius problems.
void OnTriggerEnter()
{
AudioSource source = GetComponent<AudioSource> ();
source.Play ();
}
The scene game Object with this code, have an AudioSource and one audioclip configured, and her collider set to Trigger?
All objects you need to make the Trigger called have a Collider and almost one have a Rigidbody?
Notes: Trigger events are only sent if one of the Colliders also has a Rigidbody attached.
What is exactly the problem? OnTriggerEnter() its never called?
Are you getting any error on console type NullReference?
Well I tried this same method with a completely new collectible and it worked, but the ones I need to work are from the 1st script above, which allows me to place them in a circle rather than by hand. The issue is that, for collectibles made from the first script, no sound occurs when the player object collides with the collectible.
I hope I'm being clear.
Your answer
![](https://koobas.hobune.stream/wayback/20220612133039im_/https://answers.unity.com/themes/thub/images/avi.jpg)