I’m trying to trigger a sound every time a object becomes visible – but only at the beginning of that phase. And I want to reset this once the object moves out of sight.
At the moment the sound is triggered again and again – during the whole period the object is intercepted. But I’d like it to play once, set back, and the next time it is intercepted to be played once again.
Thanks!
public class RayCastTest : MonoBehaviour {
void Update () {
Vector3 fwd = transform.TransformDirection(Vector3.forward);
float rayLength = 4.25f;
if (Physics.Raycast(transform.position, fwd, rayLength))
audio.Play();
}
}
To do something every time an object becomes visible you can use the OnBecameVisible() function. It is called by unity every time the object comes into view of a camera.
Because the condition is returning true once it becomes true. You need to check further is sound played before? for that, use boolean which checks whether sound was played earlier after object was visible. If so, then bool will be true and it wont play sound again till the bool set to false in invisibility of an object.