Hello! i have been wondering how i could change the scene on collision because i am making a 2d / 3d endless runner game and i need it to change from a 2d scene to a 3d scene on collision. any idea how to do this?
This old thread is the top of the list for this fix, so here’s an updated-for-2017 answer:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Make sure to add this, or you can't use SceneManager
using UnityEngine.SceneManagement;
public class Lvl02_Exit : MonoBehaviour {
void OnTriggerEnter(Collider other){
//other.name should equal the root of your Player object
if (other.name == "AdvancedPlayer") {
//The scene number to load (in File->Build Settings)
SceneManager.LoadScene (3);
}
}
}
This script is attached to the Collider (Cube with MeshRenderer turned off) at the end of the level. Whenever the Player (in my case, it’s named “AdvancedPlayer”… thanks UFPS!) runs into the Collider, it loads the next Scene.
If you’re working with 2D Physics components you need the use those collision functions
void OnCollisionEnter2D(Collision2D col){
if(col.transform.tag == "Player"){
Application.LoadLevel( "SomeScene" );
}
}
So no one goes insane like I did, the original was for a 2D scene where as the updated code is for a 3D scene. All you have to change is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Make sure to add this, or you can't use SceneManager
using UnityEngine.SceneManagement;
public class Lvl02_Exit : MonoBehaviour {
void OnTriggerEnter2D(Collider2D other){
//other.name should equal the root of your Player object
if (other.name == "AdvancedPlayer") {
//The scene number to load (in File->Build Settings)
SceneManager.LoadScene (3);
}
}
}
All colliders need to be set to 2D.
,So no one goes insane like I did. The updated code was written for 3D.
If you are doing 2D then you have to change it like so:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Make sure to add this, or you can't use SceneManager
using UnityEngine.SceneManagement;
public class Lvl02_Exit : MonoBehaviour {
void OnTriggerEnter2D(Collider2D other){
//other.name should equal the root of your Player object
if (other.name == "AdvancedPlayer") {
//The scene number to load (in File->Build Settings)
SceneManager.LoadScene (3);
}
}
}
Updated 2019
void OnCollisionEnter2D(Collision2D coll)
{
//If it touches the player.
if (other.name == “Player”)
{
SceneManager.LoadScene(“Test”);
}
},void OnCollisionEnter2D(Collision2D coll)
{
//If it touches the player.
if (other.name == “Player”)
{
SceneManager.LoadScene(“Test”);
}
}
Updated 2019