"on click" basics

From the Unity pages, a simple way to detect your mouse clicks -

using UnityEngine;
using System.Collections;

// Detects clicks from the mouse and prints a message // depending on the click detected.

public class ExampleClass : MonoBehaviour { void Update() { if (Input.GetMouseButtonDown(0)) Debug.Log("Pressed primary button.");

if (Input.GetMouseButtonDown(1)) Debug.Log("Pressed secondary button.");

if (Input.GetMouseButtonDown(2)) Debug.Log("Pressed middle click."); } }

 

 And from this site -

void Update(){
if (Input.GetMouseButtonDown(0))
     {
     Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
     RaycastHit hit;
     if (Physics.Raycast(ray, out hit)) 
        {
         Destroy(hit.transform.gameObject);
         }
    }
}
 
 You'll want to put the 2nd script in the Camera Object. And it only works if the objects in your scene have collision components attached to them.
 
 
Also from that site, move an object to where you click. Attach this to the target object, eg a large grid & assign the "cube" object in the Inspector -
 
public GameObject cube;
Vector3 targetPosition;
 
void Start () {
 
targetPosition = transform.position;
}
void Update(){
 
if (Input.GetMouseButtonDown(0)){
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
 
if (Physics.Raycast(ray, out hit)){
targetPosition = hit.point;
cube.transform.position = targetPosition;
}
}
}
 

Comments

Popular posts from this blog

setting VFX graph properties using C#