Hello all. I am “trying” to make a game, and encountered a lot of problems. Fortunately, this forum helped me a lot surpassing them Now, here is my new problem that i encounter.
I created a collider which is supposed to load a scene (named here “lvl1_sc2” ) when the player is on this collider, and only when he puches the “up” button. It worked perfectly until i tried to make it load after a delay of 2 sec. Now, nothing works !
I am new on Unity and on C, so i tried to get codes from here and there…
Here are the script i am using. Any help would be greatly welcome
P.S : ( DevantPorte.cs is the script i used on the collider, which is supposed to load the LoadLevel.cs )
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class DevantPorte : MonoBehaviour
{
public GameObject player;
public PlayerMovement2D PlayerMovement2D;
public Rigidbody Rigidbody;
public string NewLevel = "lvl1_sc2";
void OnTriggerStay(Collider other)
{
if (other.gameObject == player)
{
float vertical = Input.GetAxis("Vertical");
PlayerMovement2D.hasVerticalInput = !Mathf.Approximately(vertical, 0f);
if (vertical > 0.0f)
{
//SceneManager.LoadScene(NewLevel);
StartCoroutine(LoadLevel.Loader);
}
}
}
void Update()
{
}
}
And the second one :
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class LoadLevel : MonoBehaviour
{
public string NewLevel = "lvl1_sc2";
public static IEnumerator Loader;
void Start()
{
print("Starting " + Time.time + " seconds");
Loader = WaitAndPrint(2.0f);
StartCoroutine(Loader);
print("Coroutine started");
}
private IEnumerator WaitAndPrint(float waitTime)
{
yield return new WaitForSeconds(waitTime);
print("Coroutine ended: " + Time.time + " seconds");
SceneManager.LoadScene(NewLevel);
}
}
In LoadLevel You are starting the coroutine in the start method in line 16, i’m not sure you need to do that. if the script is attached to an active game object the level is supposed to load when Start is called. if it is not then when you call the load coroutine from the other script it will not have any coroutine referenced.
also in DevantPorte will start the coroutine every frame the up key is pressed and the player is inside the trigger, you need to assign the started coroutine to a local variable and check if the courotine already running\exist ie is not null.
you might want to make LoadLevel class a static class that dosen’t inherit from MonoBehaviour.
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public static class LoadLevel
{
public static IEnumerator WaitAndPrint(float waitTime, string levelName)
{
yield return new WaitForSeconds(waitTime);
print("Coroutine ended: " + Time.time + " seconds");
SceneManager.LoadScene(levelName);
}
}
and then call the coroutine directly in the DevantPorte script StartCoroutine(LoadLevel.WaitAndPrint, NewLevel );