Play animation on click (178738)

Hi guys,

I know this is probably obvious though i cant seem to work it out.

i have a treasure chest with animation on it, when i click on the chest with the mouse, i want unity to play that animation.

This is the code i have though i cant seem to get it working…

using UnityEngine;
using System.Collections;

public class ClickMesh : MonoBehaviour {
private string getName;
	// Use this for initialization
	void Start () {
	
	}
	
void Update(){
   if (Input.GetMouseButtonDown(0)){ // if left button pressed...
     Ray ray = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
     RaycastHit hit;
     if (Physics.Raycast(ray, out hit)){

      getName = hit.collider.name;
     	  Debug.Log("Mouse Down Hit the following object: " + hit.collider.name);
     	  getName.GetComponent<Animation>().Play("open");
     }
   }
 }
}


any help would be great :)

Do you get the "Mouse Down..." message confirming hit is on chest? Does chest have a "open" animation (spelling/capitalization exact match )? Do you get an error?

Does it have a collider to be hit by the Raycast?

hi guys, so this is the error im getting: Assets/Mouse Events/ClickMesh.cs(16,8): error CS0029: Cannot implicitly convert type string' to UnityEngine.GameObject' I have an animation called "open" (all lower case) and yes the console does trace out that i have clicked the object. I also have a box collider attached too, i just cant figure out the syntax to get the animation to play :( cheers

it means that you should do it in 3D but that's just my opinion because my workflow is in 3d and i think it would be easier and better

1 Answer

1

The problem is on the getName.GetComponent it expects it to be GameObject to work instead you have declared it as string. All you have to do is change the getName to “private GameObject getName” and then set it with getName = hit.collider.gameObject; . or something like this

void Update(){
    if (Input.GetMouseButtonDown(0)){ // if left button pressed...
      Ray ray = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
      RaycastHit hit;
      GameObject go = null;
      if (Physics.Raycast(ray, out hit)){
       getName = hit.collider.name;
       go = hit.collider.gameObject;
            Debug.Log("Mouse Down Hit the following object: " + hit.collider.name);
            //also you gonna need to chech if the object is actually a chest
           if(getName == "chest")
                   go.GetComponent<Animation>().Play("open");
      }

Thank you so much, yes i changed it to a GameObject and it all worked. :)

@a161803398874 but if I don't do a tile system then what else do I do?