Hi! I’m trying to play footsteps sounds when we are in a trigger and we are walking. This script didn’t work… The comments explain further, thanks for helping in advance.
#pragma strict
//variables
var WalkingInTrigger : boolean = false;
var IsInTrigger : boolean = false;
//when enter trigger:
function OnTriggerEnter(other : Collider){
//when tag = player and press W
if(other.tag == "Player" && Input.GetKey(KeyCode.W)){ //remember to tag player
//Change to true
WalkingInTrigger = true;
}
//And if the tag is player && is in Trigger (its in the OnTriggerEnter function)
if(other.tag == "Player"){
//Change to true
IsInTrigger = true;
}
}
//When we exit the trigger:
function OnTriggerExit(other : Collider){
//And the tag = player
if(other.tag == "Player"){
//Stop the audio
audio.Stop();
}
}
//function updates
function Update() {
//when WalkingInTrigger & IsInTrigger are true:
if(WalkingInTrigger == true && IsInTrigger == true){
//Play audio
audio.Play();
}
//But, if only IsInTrigger is true:
if(IsInTrigger == true && WalkingInTrigger == false){
//Dont play the audio. (So stop it)
audio.Stop();
}
}
i restructured you script so it uses less condition checks. I also moved the input check into update. Befor it onlc checked whether the player walked when he entered the trigger. Try this out:
#pragma strict
//variables
var WalkingInTrigger : boolean = false;
var IsInTrigger : boolean = false;
//when enter trigger:
function OnTriggerEnter(other : Collider) {
//If the tag is player && is in Trigger (its in the OnTriggerEnter function)
if(other.tag == "Player"){
//Change to true
IsInTrigger = true;
}
}
//When we exit the trigger:
function OnTriggerExit(other : Collider) {
//And the tag = player
if(other.tag == "Player"){
//Stop the audio
IsInTrigger = false;
WalkingInTrigger = false;
}
}
//function updates
function Update() {
if(IsInTrigger)
{
if(Input.GetKey(KeyCode.W)) {
WalkingInTrigger = true;
}
//when WalkingInTrigger & IsInTrigger are true:
if(WalkingInTrigger){
//Play audio ifit doesnt play already
if(audio.isPlaying) {
audio.Play();
}
}
else {
//Dont play the audio. (So stop it)
audio.Stop();
}
}
}
I dont know much about audio but I guess you can scrap the “IsWalking” variable entirely and only play the audio when they key is pressed.