I have a simple script to play an animation when the object is clicked. However, it plays when I click anywhere, not just the object. how do I fix this?
public class Turtle : MonoBehaviour
{
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0)){
GetComponent<Animation>().Play("Turtle");
}
}
}
28mitu
2
@wolfbrethren
You can use OnMouseDown() which will detect click on objects which has collider attached i.e.,
void OnMouseDown()
{
GetComponent<Animation>().Play("Turtle");
}
Or
You can use “Raycast” i.e.,
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
//Mention the game object name
if (hit.collider.gameObject.name == "Cube")
{
GetComponent<Animation>().Play("Turtle");
}
}
}
}
I hope it helps.