- Home /
one shot Sound on collision. Unity 4.0 problem.
Im trying to do so, if you for example go in to a room i want a sound to start, so I put a cube ,with "is trigger" checked, to the player to collide with and then the gameobject(cube) destroys so it doesnt play a second time when entering the room. I attach the script to the cube and ofcourse sets the players tag to "Player". I have always used this script but now, in 4.0 it doesnt work. I think the gameobject destroys before the sounds begin playing so you cant hear the sound
Script
var sound : AudioClip;
function OnTriggerEnter( hit : Collider )
{
if(hit.gameObject.tag == "Player")
{
Destroy(gameObject);
audio.PlayOneShot(sound);
}
}
Have you tried swapping the Play and Destroy lines?
audio.PlayOneShot...
Destroy(...);
Add Debug.Log statements before the if, and inside the if. Also log hit.gameObject.tag and make sure it's set to what you expect. Also, strings are case sensitive - you're checking for "Player", and in your question you mention that you set the tag to "player" (lower case "p").
Im verry new to this so i didnt rly get the Debug.log thing, but the lower case "p" where a mistake sorry.
function OnTriggerEnter( hit : Collider )
{
Debug.Log("Hit: " + hit.gameObject.tag);
if (hit.gameObject.tag == "Player")
{
Debug.Log("Hit object has Player tag");
Destroy(gameObject);
audio.PlayOneShot(sound);
}
}
When you run that, look at the console window and it should show a message when OnTriggerEnter gets called, and then another one right before the game object is destroyed. This will let you verify that the code is getting inside your if statement and actually executing the PlayOneShot.
If that works correctly, then I would try commenting out the Destroy and see if the sound plays then.
Answer by Dave-Carlile · Jan 17, 2013 at 09:50 PM
You need to destroy the object after a delay. You can do this by calling Invoke and passing in the time. The time should be longer than it takes to play the sound.
So...
...
{
audio.PlayOneShot(sound);
Invoke(DestroySelf, 3)
}
void DestorySelf()
{
Destroy(gameObject);
}
if you mean secounds, I only have to put:
Example: yield WaitForSeconds (10);
Between ...PlayOneShot and Destroy... lines
Answer by $$anonymous$$ · Jan 18, 2013 at 03:53 PM
Destroy()
has a time argument, this is the cleanest to do it:
function OnTriggerEnter( hit : Collider )
{
if(hit.gameObject.tag == "Player")
{
if (!alreadyPlayed)
{
audio.PlayOneShot(sound);
alreadyPlayed = true;
Destroy(gameObject, 5);
}
}
}
Like i said before, im still really newb to this :P Could you explain abit please? would be much appreciated.