I try to load next scene after collision after some time. I am new to unity and i dont get how to manage time in unity. I tried almost everything.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
void checkFinish(RaycastHit hitInfo)
{
if (hitInfo.collider.gameObject.tag == "Finish")
{
StartCoroutine(delay());
}
}
IEnumerator delay()
{
yield return new WaitForSeconds(2f);
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex 1);
}
}
Error code always shows up with Assets\Scenes\script\LaserBeam.cs(114,13): error CS0103: The name 'StartCoroutine' does not exist in the current context. Can anyone explain what is wrong with it?
CodePudding user response:
Your code does not appear to be a part of any class that inherits from MonoBehaviour
, which is required for the StartCoroutine
method.
A simple fix would be encapsulating your code inside a class that inherits from MonoBehaviour
. Based on the code, I propose SceneLoader
would be a fitting name, but any name would work.
public class SceneLoader : MonoBehaviour
{
...
}
There are also some syntax issues with your code, such as incorrectly placed brackets, naming practices, and inefficient tag
comparison. I would recommend that you touch on the basics of C# programming in Unity by visiting the plethora of available tutorials.
Overall, a more neatly formatted version of your code would look as follows:
public class SceneLoader : MonoBehaviour
{
private void CheckFinish(RaycastHit hitInfo)
{
if (hitInfo.collider.gameObject.CompareTag("Finish"))
{
StartCoroutine(Delay());
}
}
private static IEnumerator Delay()
{
yield return new WaitForSeconds(2f);
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex 1);
}
}
You could also substitute the Coroutine
with an Invoke()
method, that takes a delay
parameter. But I leave that for you to decide :)