- Home /
Animation plays for every instance of an object
I created a method for detect clicking on an object in scene and play a animation attached to a canvas the code is :
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000, TurretSellLayer))
{
anim.SetTrigger("Luanch");
Debug.Log("Noooooooooooooow");
}
}
the code works fine but when ever i click one of them , animation plays for every instantiated prefab in the scene
Answer by Seth-Bergman · Sep 22, 2018 at 07:33 AM
You should google it, this is a common objective, odds are someone’s asked it before.. you need to check against the specific instance somehow, such as checking the name: https://answers.unity.com/questions/615771/how-to-check-if-click-mouse-on-object.html Not sure if every instantiation would have a unique name off-hand, if not you may have to set each on creation to use name, or use some other variable or whatever feels good.. probably the cleanest way is something like: if (hit.gameObject == gameObject) etc.
@Seth-Bergman Thanks a lot RaycastHit does not contain a definition for gameObject but you gave me the Idea and now I am checking for its transform and works like a charm Thanks again
Glad to help :) (ps please use “add comment” in the future for reply)
Answer by SkaredCreations · Sep 20, 2018 at 09:53 AM
If you're attaching this script to all your instantiated objects then it's normal that you're having this behavior, since you're only checking for Input.GetMouseButtonDown and it's called for every object that has this script attached.
If instead you've attached this script to one only object in the scene then may be that your 'anim' member is a reference to the original prefab, in which case it's also 'normal' how it behaves since the changes to a prefab is reflected in all its instances.
Your answer
Follow this Question
Related Questions
C# - Trigger Animation with Raycasting? 1 Answer
How to select an object with TOUCH and change its animation 2D 1 Answer
Raycasting Help 1 Answer
Door only opening once on Raycast 1 Answer