- Home /
Adding Sound To Collectable Object
I'm trying to play a sound when the tagged "Player" picks up a collectable tagged "Pick up" I tried 4 hours worth of coding and can't figure it out. Any ideas? I got the objects to disappear and be collected in numeral values already, just need to figure out how to get the sound when it disappears/inactive. This is for Unity 5 by the way.
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag ("Pick Up"))
{
other.gameObject.SetActive (false);
count = count + 1;
SetCountText ();
}
}
^^^ This is the Player coding at which the Object is not Destroyed but Inactive when collided
#pragma strict
function OnTriggerEnter(otherObj: Collider){
if (otherObj.tag == "Player"){
GetComponent.<AudioSource>().Play();
}
else {
GetComponent.<AudioSource>().Stop();
}
}
^^^ This is the coding used on the "Pick Up" item trying to use an Audio Source type Don't know if this is the right coding but I have tried manipulating a DestroyObject script and still cant figure it out. Thanks in advance guys, you all are always so good with replying.
Answer by hexagonius · Oct 31, 2015 at 11:50 AM
The problem here is, that the pickup tries to play sound, while at the same time the player disables it, effectively avoiding it to be played. Either some other gameobject is responsible for playing sounds (which is more easy I think), or you'd need an alternative to acutally disabling the whole pickup gameobject. You could try this:
remove "other.gameObject.SetActive (false);" from the player
change the pickup to this:
function OnTriggerEnter(otherObj: Collider){ if (otherObj.tag == "Player"){ GetComponent.<AudioSource>().Play(); GetComponent.<Collider>().enabled = false; GetComponent.<Renderer>().enabled = false; } }
Yes I was thinking about using a "WaitForSeconds" on the Player so it was able to play the sound before it was disabled. But let me try your option and see how it works. Thanks!
Hmm no luck. What about if I add a script to the player when he collides with the prefab/pickup?
sure, let him play the sound, why not :) everything is allowed