Trigger animation of one game object by clicking on another game object
Hi everybody,
I have an game object with a script attached. If I click the game object, it's animation will play (it's a puppet walking to the left). Now I want the puppet (game object) to walk to the left if I click another game object.
Is it possible to use the same code and attach it to the other game object and then tweak the code a bit? Or do I have to do this in a different way.
This is the code I use now. Thank you for answering!!!!
using UnityEngine;
using System.Collections;
public class Walk : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Linecast(worldPos, worldPos);
if (null != hit && hit.collider.gameObject == gameObject)
{
Animator anim = GetComponent<Animator>();
if (null != anim)
{
Debug.Log("Playing Lopen");
anim.Play("Lopen");
}
}
}
}
}
,
It will work fine but you need a reference to the puppet sum$$anonymous$$ like :
Animator anim = Puppet.GetComponent<Animator>();
Thank you for your answer. I was actually looking that direction. But when I add Puppet.GetComponent etc. the error reads 'The name Puppet does not exist in current context'.
Can't figure it out. $$anonymous$$aybe you can help me again.
Thank you! Cheers!
Answer by jonahsrocket · May 29, 2016 at 10:15 PM
Hi there,
I managed to solve my problem by using something completely different. I used this tutorial. Then I attached the animator of the animation that I wanted to run (the puppet) on the other game object. So if I click the other game object, the puppet will walk to the left. Just what I wanted. I am a happy guy!
Thanks anyway for answering!!!!!
Cheers!
Answer by PhantomSarcasm · May 25, 2016 at 09:53 PM
the problem is that with this code specifies these activating the animation of walking to the left ... I think. you would have to put another but changing the animation of walking by you to have to go right. or you can even use more switch to choose the animation given ... know how to use the switch.
//this variable are placed above not within the functions
public int valor;
if(null!=anim)
{
//
switch(valor)
{
case 1:
//the animation 1
animation.play("lopen");
break;
case 2:
//the animation 2
//say the right but not like this your animator
// I do not know
//
anim.Play("right");
break;
default:
break;
}
}
forgive my English use google translator...