Created
April 23, 2017 16:41
-
-
Save BenTristem/3c3636b7c54bc60bff367e5abdcfa743 to your computer and use it in GitHub Desktop.
Simple audio trigger with layer filter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
public class AudioTrigger : MonoBehaviour | |
{ | |
[SerializeField] AudioClip clip; | |
[SerializeField] int layerFilter = 0; | |
[SerializeField] float triggerRadius = 5f; | |
[SerializeField] bool isOneTimeOnly = true; | |
[SerializeField] bool hasPlayed = false; | |
AudioSource audioSource; | |
void Start() | |
{ | |
audioSource = gameObject.AddComponent<AudioSource>(); | |
audioSource.playOnAwake = false; | |
audioSource.clip = clip; | |
SphereCollider sphereCollider = gameObject.AddComponent<SphereCollider>(); | |
sphereCollider.isTrigger = true; | |
sphereCollider.radius = triggerRadius; | |
} | |
void OnTriggerEnter(Collider other) | |
{ | |
if (other.gameObject.layer == layerFilter) | |
{ | |
RequestPlayAudioClip(); | |
} | |
} | |
void RequestPlayAudioClip() | |
{ | |
if (isOneTimeOnly && hasPlayed) | |
{ | |
return; | |
} | |
else if (audioSource.isPlaying == false) | |
{ | |
audioSource.Play(); | |
hasPlayed = true; | |
} | |
} | |
void OnDrawGizmos() | |
{ | |
Gizmos.color = new Color(0, 255f, 0, .5f); | |
Gizmos.DrawWireSphere(transform.position, triggerRadius); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment