- Home /
2D Load scene by clicking Object
Hello everyone! I'm working on switching scenes in my project. I would like to do so by clicking one of my objects placed in the scene. My object has Rigidbody2D and a 2D Box Collider. It also has a child that changes the sprite when moused over.
I have tried to use this code:
function Update () {
if(Input.GetMouseButton(0))
Application.LoadLevel("NextLevel");
}
But then when I click anywhere on the scene it will change and not by clicking the specific object. I also tried to use Ray casting by using this code:
void Update(){
if (Input.GetMouseButtonDown(0)){ // if left button pressed...
Ray ray = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit)){
Application.LoadLevel("NextLevel");
}
}
}
But that doesn't do anything at all.
I'm very new to Unity. Thank you very much in advance for looking at this! :-)
Answer by FortisVenaliter · May 12, 2015 at 09:23 AM
You say "It also has a child that changes the sprite when moused over."
If you have mouse over working there, then I would use the same functionality to determine whether the mouse is over the object. If, and only if, that is true, then you run your check for the mouse button and the scene changing.
You're definitely on the right track, but I think Physics Raycasting might be overkill for what you're trying to do.
Answer by PixelSpartan · May 11, 2015 at 09:01 PM
This is in JavaScript. This script goes on the main camera. The button must be named "Play" (Without "" ) and must have a box collider MUST BE SET AS A TRIGGER.
//Type the name of the scene to load in the inspector.
var SceneToPlay : String ;
var hit: RaycastHit;
function Update (){
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Input.GetMouseButtonDown(0)){
if (Physics.Raycast (ray, hit , Mathf.Infinity)){
if (hit.collider.name == "Play") { Application.LoadLevel(SceneToPlay); }
} } }
Your answer
![](https://koobas.hobune.stream/wayback/20220613195316im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Detect UI Panel click 2 Answers
how can i make a object look at the mouse click only in the y axis? 1 Answer
Moving a 3d object in unity on mouse click with click to move controller 1 Answer
Mouse clicking on an object (Raycast.hit) for another object to connect to it? 0 Answers
How To Detect MouseClick Using Raycast Java Script 0 Answers