- Home /
My first script, and I need some help.
Made a previous post concerning playing audio on collision, and ended up with this code.. #pragma strict
function Start () {
var play;
if pause = true
function OnCollisionEnter(collision : Collision) {
// Debug-draw all contact points and normals
for (var contact : ContactPoint in collision.contacts) {
Debug.DrawRay(contact.point, contact.normal, Color.white);
}
// Play a sound if the coliding objects had a big impact.
if (collision.relativeVelocity.magnitude > 2)
audio.Play();
}
var pause;
if play = true
function OnCollisionEnter(collision : Collision) {
// Debug-draw all contact points and normals
for (var contact : ContactPoint in collision.contacts) {
Debug.DrawRay(contact.point, contact.normal, Color.white);
}
// Play a sound if the coliding objects had a big impact.
if (collision.relativeVelocity.magnitude > 2)
audio.Pause();
}
}
function Update () {
}
I know there's stuff wrong with it, but could someone just blunty tell me or fix it so I can learn from a side by side comparison? I'm not very good at learning in bits and pieces.
Thans - Sir Paddles of Loxely
I forgot to say what I want it to do.
I want the object to play/pause music when the player runs into it, or it is collided with in general.
I just want to say that the way I use sounds, and it works well, is by making a variable of AudioSource, and then I do AudioSource.PlayClipAtPoint(yourSound). At least something like that. But that's for playing a sound. So in your case, do you have an audio source?
Answer by robertbu · Jan 28, 2013 at 05:50 AM
Here is a rewrite of your script.
var playing = false;
function OnCollisionEnter(collision : Collision)
{
// Debug-draw all contact points and normals
for (var contact : ContactPoint in collision.contacts) {
Debug.DrawRay(contact.point, contact.normal, Color.white);
}
// Play/pause a sound if the colliding objects had a big impact.
if (collision.relativeVelocity.magnitude > 2) {
if (playing)
audio.Pause();
else
audio.Play();
playing = !playing; // flips value
}
}
A couple pointers. You cannot have the same function twice in a script as you have OnCollisionEnter(). You shouldn't nest functions as you have with your OnCollisionEnter's inside of the Start() function. You should lookup the syntax of the if statment and also take a look at how elements are compared. The '=' by itself is for assignment not comparison.
Ah thank you very much. It's a lot easier to figure this stuff out with a right and a (extremely) wrong to look at, thank you. I obviously still have much learning to do.
Your answer
![](https://koobas.hobune.stream/wayback/20220613091715im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
On Collision, Play Sound If Button Is Pressed 1 Answer
help sound on collision when key down 2 Answers
OnTriggerExit stop audio 1 Answer
How to play an audio one shot clip on a collision 1 Answer
Audio on Collision Issue 1 Answer