The question is answered, right answer was accepted
(FIXED) OnTrigger waitforseconds not working.
I'm trying to make it so when my character touches the Trigger It's plays an audio file and then waits to the time the audio is done to go to a different scence, the trigger works and the audio plays, but for some reason the timer does not start and it does not switch to the different scene. Here's my code:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class SoundCollideRestart : MonoBehaviour
{
AudioSource audioData;
IEnumerator OnTriggerEnter(Collider other)
{
audioData = GetComponent<AudioSource>();
audioData.Play(0);
yield return new WaitForSeconds(1);
SceneManager.LoadScene(0);
}
void OnTriggerStay (Collider other)
{
}
void OnTriggerExit (Collider other)
{
gameObject.GetComponent<BoxCollider>().isTrigger = false;
gameObject.GetComponent<BoxCollider>().enabled = false;
}
}
Is there any chance the object holding this script is destroyed by another script?
probably not but the gameObject.GetComponent().isTrigger = false; gameObject.GetComponent<BoxCollider>().enabled = false;
could be causing it so I shall try to remove it
Answer by KidCanada7 · Jun 22, 2021 at 03:13 AM
I fixed it with this updated code:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class SoundCollideRestart : MonoBehaviour
{
AudioSource audioData;
public float wait_time = 5f;
void OnTriggerEnter(Collider other)
{
audioData = GetComponent<AudioSource>();
audioData.Play(0);
}
IEnumerator OnTriggerStay (Collider other)
{
yield return new WaitForSeconds(wait_time);
SceneManager.LoadScene(0);
}
void OnTriggerExit (Collider other)
{
gameObject.GetComponent<BoxCollider>().isTrigger = false;
gameObject.GetComponent<BoxCollider>().enabled = false;
}
}
Follow this Question
Related Questions
OnTriggerEnter Issue - Collider problem 0 Answers
Collision or Triggers both not working. 3D. 1 Answer
IENumerator does not work 0 Answers
Trying to add a delay to an Instantiate in a For Loop 0 Answers
RayCast From Centre of Camera 1 Answer