- Home /
Sound only plays once
In my game I have an object that teleports to a platform that is a little ways away. I have a sound play when my ball teleports. The problem is that if I teleport the ball again, the sound won't play. I want the sound to only play once when the teleport happens. Here is my code:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Teleport : MonoBehaviour {
public Transform target2;
public AudioSource wew;
public bool win;
bool playWinSound = true;
// Use this for initialization
void Start () {
wew = GetComponent <AudioSource> ();
}
// Update is called once per frame
void Update () {
if (win == true) {
if (playWinSound) {
wew.Play ();
playWinSound = false;
}
}
}
void OnCollisionEnter (Collision col) {
if (col.gameObject.tag == "good") {
this.transform.position = target2.position;
win = true;
}
}
}
Answer by nt314p · Aug 02, 2017 at 12:21 AM
A simple mistake, easily overlooked: You aren't setting playWinSound back to true. The if statement to play the sound will never be true since playWinSound will always be false
Here's your new code for the OnCollisionEnter (which I am assuming runs when you hit the teleportation pad):
void OnCollisionEnter (Collision col) {
if (col.gameObject.tag == "good") {
this.transform.position = target2.position;
win = true;
playWinSound = true
}
}
Thank you so much. I'm kinda new to program$$anonymous$$g and stuff.
If this is the correct answer, you can mark it so that other people can benefit from this question.