Tuesday, October 31, 2017

Different ways of enabling mouse click as event trigger in Unity via scripting

For a 2D object/sprite:
Option 1:
1. In the script file, include using UnityEngine.EventSystems; at the top.
2. Implement the PointerClick interface 
3. Attach the script to the 2D sprite and make sure that a 2D collider (e..g box collider 2D) is attached to it.
4. Select the camera and attach Physics 2D raycaster to it.

using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;

public class clickTester : MonoBehaviour, IPointerClickHandler  
 {  
      public void OnPointerClick (PointerEventData eventData)  
      {  
           //do something here, e.g. change colour of sprite.  
           GetComponent<SpriteRenderer>().color = new Color(1f,0.3f, 0.30196078f);  
           print ("Pointer click");  
      }  
 }  

Source: https://stackoverflow.com/questions/37452457/unity-3d-enabling-mouse-pointer-as-a-event-triggers-pointer-enter-exit/37456107#37456107


Option 2:
1. Ensure the 2D sprites have a 2D collider attached to them.
2. Attach a script file to the camera with the code below.
 using System.Collections;  
 using UnityEngine;  

 public class clickTester: MonoBehaviour {  
   void Update()  
   {  
     if (Input.GetMouseButtonDown(0)) //This is left mouse button click 
     {  
       //Converting Mouse Pos to 2D (vector2) World Pos  
       Vector2 rayPos = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);  
       RaycastHit2D hit = Physics2D.Raycast(rayPos, Vector2.zero, 0f);  
       if (hit)  
       {  
       //do something here, e.g. change colour of sprite.   
       GetComponent<SpriteRenderer>().color = new Color(1f,0.3f, 0.30196078f);   
       print ("Pointer click");   
       }  
     }  
   }  
 }  




For a UI button:
1. In the script file, include using UnityEngine.UI; at the top.
2. Make a public void method and give it a name
3. In the button, add an Event Trigger component -> Add New Event Type -> Pointer Click.
4. Drag the gameobject the script is attached to into the pointer click.
5. Choose the public void method created.
 using System.Collections;  
 using System.Collections.Generic;  
 using UnityEngine;  
 using UnityEngine.UI;  

 public class button : MonoBehaviour  
 {  
      public void changeColour(){  
           //Do something here, e.g. change colour of button.  
           GetComponent<Image>().color = Color.green;  
           print ("testing changeColour");  
      }  
 }  

No comments:

Post a Comment