- Home /
Event to be triggered after constant contact with gameobject
I have a trigger zone which playes audio when entered. I can't figure out how to make a timer so that if the player stays in the trigger zone for a certain amount of time, constant contact it starts a certain event (the death animation) any help would be great thanks. Just need a timer parameter or something like that
{
public class EnterDarknessScript : MonoBehaviour
{
public AudioClip Hurry;
void Start()
{
GetComponent<AudioSource>().playOnAwake = false;
GetComponent<AudioSource>().clip = Hurry;
}
//Plays the sound whenever in trigger area
void OnTriggerEnter()
{
GetComponent<AudioSource>().Play();
}
}
} Thanks
Answer by Priyanka-Rajwanshi · Apr 08, 2018 at 03:54 AM
@brewster2110 Try this:
float timeInterval = 2;
float counter;
void OnTriggerEnter(Collider collider)
{
counter = 0;
GetComponent<AudioSource>().Play();
}
void OnTriggerExit(Collider collider)
{
counter = 0;
}
void OnTriggerStay(Collider collider)
{
counter += Time.deltaTime;
if ( counter > timeInterval)
{
//Die
counter = 0;
}
}
I modified this a little bit and it's great! Thank you so much :)
Answer by Gordrik · Apr 08, 2018 at 01:32 AM
float duration = 2;
float counter;
void OnTriggerEnter()
{
counter += Time.deltaTime;
if (duration <= counter )
{
Debug.Log("Counting every 2 seconds");
counter = 0;
}
}
Let me know if it's working properly with triggers
Tried adding that but not sure if I did so properly
{
public class EnterDarknessScript : $$anonymous$$onoBehaviour
{
public AudioClip Hurry;
void Start()
{
GetComponent<AudioSource>().playOnAwake = false;
GetComponent<AudioSource>().clip = Hurry;
}
//Plays the sound whenever in trigger area
float duration = 2;
float counter;
void OnTriggerEnter()
{
counter += Time.deltaTime;
if (duration <= counter )
{
Debug.Log("Counting every 2 seconds");
GetComponent<AudioSource>().Play();
}
}
}
}
Nothing happens when entering trigger area
Your answer
Follow this Question
Related Questions
How to see minutes in the timer's box? 1 Answer
Collison detection not working? 1 Answer
Where to attach a script 1 Answer
Ontrigger not working with npc 0 Answers