- Home /
Get GameObject That Was Last Clicked?
I know how to check if a gameobject was clicked using RayCast but what is the best way to check the last object that was clicked?
I was thinking something like a for loop that goes through every object and does a RayCast check but that seems like it'd take too much memory for something so simple.
(C# preferably please)
Answer by clunk47 · Jul 21, 2013 at 04:32 PM
Simply use a variable named something like "lastClicked". The way I have the raycast here isn't how people usually do it. The way I have it, only updates the ray on mouse click, instead of every frame.
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
GameObject lastClicked;
Ray ray;
RaycastHit rayHit;
void Update()
{
if(Input.GetMouseButtonDown (0))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out rayHit))
{
lastClicked = rayHit.collider.gameObject;
if(lastClicked != null)
print(lastClicked.name);
}
}
}
}
If this works for you and resolves you issue, please be so kind to Vote up / Accept my answer so that others will know this has been resolved :D
in unity2D, or 2d games, this will work as well? or do you suggest a better way?
Answer by DaveA · Jul 21, 2013 at 08:10 AM
Have it SendMessage to a single ClickHandler script, pass it the unique name or some other unique identifier, or just a reference to itself.
Your answer
Follow this Question
Related Questions
C# Track Mouse Cursor Movement Speed 2 Answers
C# Decrease Mouse Sensitivity Camera Move 0 Answers
C# moveOnMouseClick Rotation 2 Answers
C# Mouse Look (Input.GetAxis("MouseX&Y")) 0 Answers
C# Input.GetKey("Tab") Double Tap 1 Answer