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! :slight_smile:

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.

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);
}

}
}
}