I am trying to make it when the player touches a certain object they will be put into the next scene. In my case the object that the player must collide with is off screen so when the player moves off screen they will touch the object teleporting them. This is a 2D game by the way
Use the OnCollisionEnter message-method in a MonoBehaviour.
[SerializeField]
private string nextSceneName;
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player"))
SceneManager.LoadScene(nextSceneName);
}
Both the player and the object which changes the scene need to have a Collider2D attached. Attach the script from above to the latter and the scene specified with nextSceneName will be loaded.
ok, that’s fairly straight forward. Look up “OnCollisionEnter” or “OnTriggerEnter” and SceneManagement.LoadScene.
Might also need SceneManagement.GetActiveScene and Scene.buildIndex depending on how you’re working out the “next scene”.
give it a go, if you can’t figure it out post your attempt and we’ll help with any problems
I changed the nextSceneName to my next scene name and added the other code. I added a Box Collider to the object. When I made the player touch the object it did not work? It just treated the object as a normal obstacle. I don’t know if im doing something wrong. Also I had to add usingusing UnityEngine.SceneManagement;
so I now have 3 things at the top. I had to add that for SceneManager to work
I also realized it gives me the option to define “Level 2” in the Inspector. What should I write down there?
collisions aren’t detected unless something involved has a rigidbody on it.
The exposed variable in Nik’s code is for the scene name that you want to be loaded (no idea what you’ve called your scenes… ).
@d-ostapa I do not recommend changing the name of the field to level2 because you might use this script in level 2 as well. Then the name does not fit anymore.
Instead I meant that you should change the value stored in this variable to your next scene name; So go to the inspector of this script and click on the text field right next to the variable name and put in “Level 2” or however you scene is called.
Thanks bro for the help. I am making my first game !
I’m having some trouble with a project I’m doing for school, and if anyone can help it would me much appreciated… if they can respond asap… I have an empty game object attached a circlecollider2d and a rigidbody2d to it after my first failed attempts. My player game object already has a collider and rigidbody.
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == “Player”)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
This is my code that I attached to the empty object with the collider, but nothing happens when I pass through it. It is set to Is Trigger, I’ve tried continuous and discrete detection methods but nothing is happening… I have the scenes in the build settings too.