how to use onCollision with Application.LoadLevel
i am trying to make a 2d game where the level ends after you hit a flag. right now i have this code: using UnityEngine;
public class endflag : MonoBehaviour
{
// Use this for initialization
void OnCollisionEnter(Collision col)
{
if (col.gameObject.name == "turtle")
{
Application.LoadLevel("mainMenu");
}
}
}
from everything i have looked at this should work (the code is on the flag and the players name is turtle) did i write something wrong or should i have the code on the player instead
Answer by TBruce · Nov 28, 2016 at 02:19 AM
Application.LoadLevel()
is obsolete you now need to use SceneManager.LoadScene()
. To use the SceneManager
class you need to add the UnityEngine.SceneManagement
namespace to the uses clause.
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class endflag : MonoBehaviour
{
// Use this for initialization
void OnCollisionEnter(Collision col)
{
if (col.gameObject.name == "turtle")
{
SceneManager.LoadScene("mainMenu");
}
}
}
This was useful but how would i apply this code to this:
using UnityEngine;
public class endflag : $$anonymous$$onoBehaviour {
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.name == "turtle")
Application.LoadLevel(Application.loadedLevel + 1);
}
}
thanks for all your help
You could do something like this
using UnityEngine;
using System.Collections;
using UnityEngine.Scene$$anonymous$$anagement;
public class endflag : $$anonymous$$onoBehaviour {
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.name == "turtle")
{
int sceneIndex = Scene$$anonymous$$anager.GetActiveScene().buildIndex;
if (sceneIndex < (Scene$$anonymous$$anager.sceneCountInBuildSettings - 1))
{
Scene$$anonymous$$anager.LoadScene(sceneIndex + 1);
}
}
}
}
Your answer
Follow this Question
Related Questions
Rotate camera on collision of character 1 Answer
Player cannot destroy enemy 1 Answer
Rigid Body and Collision 1 Answer
Cube wont destroy on collision 0 Answers
Player cannot destroy enemy 0 Answers