- Home /
Change level upon clicking a gameobject
I have a gameobject in my project and what I want to do is, that when it is clicked, it should take me to the next scene or level.
function Update () {
if(Input.GetMouseButton(0))
Application.LoadLevel("Level2");
}
Here's the script I have right now. This takes me to the next level whenever I click the mouse button, but I want it to take me to the next level when I have clicked on the object.
Answer by Serinx · Jan 21, 2015 at 01:43 AM
When you get the input you could do a raycast to check whether the hit is the game object that loads the next level
void Update() {
if (Input.GetMouseButtonDown(0)) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
if (hit.collider.gameObject.tag == "LevelChanger")
Application.LoadLevel("Level2");
}
}
This assumes that your object has a collider attached and is tagged "LevelChanger"
Note. I haven't tested this
Answer by Landern · Jan 21, 2015 at 01:44 AM
What your code does is takes a click indiscriminately. Create a script, attach it to your gameobject, put a collider on that game object, in the script use the function OnMouseDown(), this will react to the collider on the gameobject, read the documentation, the application load will work as your line intends.
bonus points, create a public string:
var levelName:String;
have have specify this levelname or number as a part of the string to load level.
Application.LoadLevel("Level" + levelName);
This way you can reuse the script and change the number in the inspector in the unity editor