- Home /
Clicking one prefab effects them all.
Hi. I know this is simple, but I couldn't find an answer here or elsewhere online.
I have a prefab called "cuboid" which has been copied a number of times. I'm detecting a mouse click using raycast, then printing to the debug log. The issue is that when one object is clicked, all instances print to the debug log, not just the one clicked.
The script is on each instance of the prefab:
#pragma strict
function Update ()
{
if (Input.GetMouseButtonDown(0))
{
var hit: RaycastHit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, hit))
{
if (hit.transform.name == "cuboid" )Debug.Log( "Object was clicked");
}
}
}
Can someone please indicate why this is happening and how to correct it?
Thanks
The ray is deter$$anonymous$$ed by the camera and mouse position, and you check if it hits something with a specific name. So there's nothing in that that's specific to the object the component is on. Why would you expect it to behave differently from one object to another?
So the ray hits the one object I've clicked on, which triggers the script on each object in the scene with the same name? In that case, how can I only get the object clicked to print to debug?
Thanks
What you're doing is like telling everyone in a room to scratch their nose whenever a fly lands on Fred's nose. You need to tell them to scratch their nose when a fly lands on their own nose.
So get them to look at the transform in the hit object and ask, "is it my transform?"
Answer by Spider_newgent · Feb 25, 2015 at 09:19 AM
This post contains the answer to the question, for anyone who encounters it in future:
http://answers.unity3d.com/questions/633724/want-to-be-able-to-change-color-of-individual-cube.html
Answer by Mmmpies · Feb 25, 2015 at 09:30 AM
Have you considered using OnMouseDown or OnMouseUp?
Saves bothering with a raycast and should only trigger on the cuboid under the mouse.
Also works for touch devices.
Your answer
Follow this Question
Related Questions
raycasting prefab instances 0 Answers
Placing buildings 1 Answer
Is there a quick way to replace an object with a prefab instance? 1 Answer
Gun Script 1 Answer