unity click on 2d object 1

unity click on 2d object

// Requires for the object to have a collider and this script attached
private void OnMouseDown()
{
	Debug.Log("Clicked on object!");
}

Here is what the above code is Doing:
1. We’re creating a function called OnMouseDown.
2. We’re telling Unity that this function should be called whenever the mouse is clicked on the object.
3. We’re printing a message to the console.

Now, let’s attach this script to our cube and see what happens.

Click on the cube in the Hierarchy.
Click on the Add Component button in the Inspector.
Click on New Script.
Name the script Clickable.
Click on Create and Add.
Click on the Clickable script in the Inspector.
Click on the Open button.

Now, let’s add the code above to the Clickable script.

Click on the Save button.
Click on the Play button.
Click on the cube.

You should see the message “Clicked on object!” in the Console.

Now, let’s add a second script to the cube.

Click on the cube in the Hierarchy.
Click on the Add Component button in the Inspector.
Click on New Script.
Name the script Rotator.
Click on Create and Add.
Click on the Rotator script in the Inspector.
Click on the Open button.

Now, let’s add the following code to the Rotator script:

Similar Posts