Introduction
This article is about how to detect mouse click or touch on a GameObject using C# Script in Unity
Prerequisites
Unity Environment version 2018.4.25f1
Create the project
I pressed ctrl + s to save this scene
Create the Script
Add a new C# Script, Right-click on Assets. Select Create >> C# script.
Rename the script as SceneOneScript.
Create Empty GameObject in Unity
Click on the "GameObject" menu in the menu bar. Select "Create Empty" option.
Rename the Create Empty as Scripts
Select the Right click create new scene
I am going to rename the scene as SceneTwo
Double click to open it create another script scene - Script again Right-click on Assets. Select Create >> C# script.
Rename the Script as SceneTwoScript
Create Empty GameObject in Unity
click on the "GameObject" menu in the menu bar. Select "Create Empty" option.
Rename the Create Empty as Scripts
Drag and drop your script to the scripts
Make sure to add your scenes in the Build Settings window, choose “Build Settings” Add open scene.
Double click in Scene One and it will open Visual Studio 2019, which is my programming integrated development environment (IDE) for Unity. Write the code as shown below:
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.SceneManagement;
-
- public class SceneOneScript: MonoBehaviour {
-
- void Start() {}
-
-
- void Update() {
- if (Input.GetMouseButtonDown(0)) {
- Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
- RaycastHit hit;
- if (Physics.Raycast(ray, out hit)) {
-
- if (hit.transform.name == "Cube") {
- SceneManager.LoadScene("SceneTwo");
- }
- }
- }
- }
- }
Save the Program
Create a cube in Unity.
Click on game object 3d and then I'm going to create a cube.
Click on SceneTwo open the scene
Create The Sphere in Scene View
Select GameObject, click the 3D object and pick the Sphere option. The Sphere object will be displayed in the scene view. The name is displayed in the hierarchy view.
InScene Two, double click it and it will open Visual Studio 2019, which is my programming integrated development environment (IDE) for Unity. Write the code as shown below:
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.SceneManagement;
-
- public class SceneTwoScript: MonoBehaviour {
-
- void Start() {}
-
-
- void Update() {
- if (Input.GetMouseButtonDown(0)) {
- Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
- RaycastHit hit;
- if (Physics.Raycast(ray, out hit)) {
-
-
- if (hit.transform.name == "Sphere") {
- SceneManager.LoadScene("SceneOne");
- }
- }
- }
- }
- }
Save the Program
Play the Application Click the sphere to SceneOne and Click the Cube to SceneTwo as You can see is navigating properly so this is the simple way you can tap or click on any gameobject
Summary
I hope you understood how to detect mouse click or touch on a GameObject Using C# Script in Unity.