So i have this code to enter a new scene:
using System.Collections;
using UnityEngine;
// add this line to use the SceneManagment library
using UnityEngine.SceneManagement;
public class LoadScenes : MonoBehaviour {
[SerializeField] private string loadLevel;
void onTriggerEnter(Collider other) {
if (other.CompareTag ("Player")) {
SceneManager.LoadScene (loadLevel);
}
}
}
I then add this script to the cube and select it a trigger. I then type in the scene that I want it to send me too, but when i walk into it nothing happens at all. I have tried different variations but it just doesnt seem to work.
My character that I am using is a unity asset called man in suit but I have selected its tag as "Player". Any suggestions would be great!
As Sunimal allready noted you need to fix the typo.
void OnTriggerEnter(Collider other) {
if (other.CompareTag ("Player")) {
SceneManager.LoadScene (loadLevel);
}
}
As you can see in the Screenshot below i have added a SampleScene to my build settings. There are 2 ways of adding scenes into the build
Your loadLevel field would in my case need to have the value "Scenes/SampleScene".
[SerializeField] private string loadLevel;
As you use the OnTriggerEnter method, your Player object needs to have some sort of Collider attached to it. This can be a BoxCollider, SphereCollider or some other Collider.
Note that the "Is Trigger" checkbox needs to be checked.
Else it won't act as trigger.
Edit: Thanks Eddge for correcting me. See this answer for a deeper explanation about Triggers.
You can add the RequireComponent Attribute at your class. It basically ensures you have the given type added as a component. This will also automatically add a box collider to an object, when you add this script.
[RequireComponent(typeof(BoxCollider))]
public class LoadScenes : MonoBehaviour {
/// your other code is here
}
Thanks to Sunimal for this hint!
If all this does not help, please provide an screenshot of the inspector of your Playerobject. That way we can see what components are attached to that object and how they are "configured"
To use the SceneManager to load a scene you must ensure that your scene is in the build settings, per Tobias's answer.
In all software development case does matter and it is incredibly important. OnTriggerEnter
is not the same as onTriggerEnter
, also note OnTriggerEnter(Collider col)
is not the same as OnTriggerEnter(Collision col)
In order to use any of the trigger methods there are 3 things that are a must:
The trigger event is sent to the object with the rigidbody and whatever object is the trigger, in the circumstance that both objects are triggers both will receive it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.