- Home /
How to Code to Play Animation Only When Object is Clicked (C#)
I'm having trouble with what seems like it should be a very simple problem. I can't seem to find a simple explanation or tutorial showing how to make an object respond when clicked on. I have a C# script that plays an animation when the left mouse button is clicked, but I don't know how to make it only play when the object itself is clicked, not just any place on the screen. I know this must be simple, but I have absolutely zero experience in coding anything, so I really need a simple explanation that I could apply to other objects and scripts as well. Here is my current script:
using UnityEngine; using System.Collections;
public class Shrinkscript : MonoBehaviour {
// Update is called once per frame
void Update () {
if (Input.GetMouseButton(0))
{
animation.Play("Shrink");
}
}
}
Any help is much appreciated!
Answer by IndieScapeGames · Jan 24, 2014 at 07:02 PM
Use OnMouseDown() instead. This way if you click only the object that has a collider attached to it, will it play the animation.
function OnMouseDown ()
{
hit.animation.Play("Shrink");
}
Answer by Exalia · Jan 21, 2014 at 11:02 PM
This will try to play the animation "Shrink" on anything you click on, the object needs a collider.
if(Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, 100))
{
hit.animation.Play("Shrink");
}
}
I tried this code and it tells me "parsing error." I'm not sure what's wrong.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Help with selecting and deselecting an object? 1 Answer
Best starter tutorial 3 Answers
How can I start unity fast with my C++ engine 2 Answers
Scripts that aren't in an object 2 Answers