- Home /
Load Next scene in Build Settings with collision
I am making a new 2d game with many levels. I want the next scene load when the player collides with a door that has a collider with the option "IsTrigger" marked. I have a script on the door that looks like this:
using UnityEngine;
using System.Collections;
public class Door : MonoBehaviour {
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
Application.LoadLevel(level name or number);
}
}
The script works fine but I can only load an specific scene. Can somebody please tell me a script to load the next level in the build settings when I make a collision with the door so I don't have to make a script for every level.
Thanks.
Answer by g__l · Jan 03, 2016 at 01:48 PM
using UnityEngine;
using System.Collections;
public class Door : MonoBehaviour {
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
Application.LoadLevel(Application.loadedLevel + 1);
}
}
On the documentation it say Applicatioin.loadedLevel is obsolete and to use SceneManager but i think so would be Application.LoadLevel which works so i think it should work fine. I will check. Anyway that should do the job.
Answer by Zerite · Jan 22, 2016 at 08:33 AM
First, add all your scenes in build (use File / Build Settings...)
Then use the SceneManager in your script
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class Door : MonoBehaviour {
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
{
int c = SceneManager.GetActiveScene().buildIndex;
if (c < SceneManager.sceneCountInBuildSettings)
SceneManager.LoadScene(c+1);
}
}
}
you're awesome mate! I've been taking an online course that uses an older Unity function with Application.loadedLevel and since it's obsolete in 5.3, I couldn't figure a way around it until you taught me how to use Scene$$anonymous$$anager.GetActiveScene().buildIndex; Thanks a bunch!
Good Fix for v5 unity getting rid of the obsolete api.
Awesome, great for helping me work out what I needed to do for the new way Unity works. $$anonymous$$odified to suit my needs and its perfect. Thank you very much.
Your answer
Follow this Question
Related Questions
Increment doesnt increment after the first increment 2 Answers
Loading new level after killing enemies 3 Answers
Collision not working after Loadlevel 0 Answers
raycast with events 1 Answer
Collisions not working. 1 Answer