- Home /
How can I reference an animator in another script so that it plays the desired animation when a button is clicked?
Hi, I'm currently trying to make a simulation game (kind of like tamagotchi) where you nurture a pet through different interactions. I used a sprite sheet in unity 2d and spliced them to make the different animations needed. (idle, fed, hungry, etc). And I used this code on the Pet's game object
var anim : Animator;
function Start()
{
anim = GetComponent("Animator");
}
function Update()
{
if(Input.GetMouseButton(0) == false)
{
anim.SetTrigger("NoRub");
}
}
function OnMouseOver()
{
if(Input.GetMouseButton(0))
anim.SetTrigger("Rub");
}
So that it plays the 'Rub' transition animation when you rub the pet (left mouse + hold) to make him happy and returns to idle state (which is just bobbing up and down) when you stop. Anyway, my question is how can I reference the pet animation in another script, for example a 'feed button'? so it triggers the animation after a click and then reverts back to idle as usual.
I'm not the best at coding and I was wondering if anyone can help me create a variable in the other scripts which is an animator type so that this could work? In one attempt, i tried dragging the animator from the pet into the other script's swatches in the inspector but the feedbutton turned into the pet.
//drag an object with an animation component into this in the inspector
var objectWithAnim : Animation;
function Start () {
objectWithAnim.Play("animation name");
}
Answer by HappyMoo · Jan 08, 2014 at 10:46 PM
You need to trigger NoRub in every frame if you're not rubbing? Why not have a bool "rubbing" instead a rub trigger and stay in the state a long as rubbing=true? Only leave to idle if rubbing=false.
Now you could reference the animator of another object direclty:
var datAnim = datOtherObject.GetComponent("Animator");
But I think that's bad style and you end up with animator code spread out through your whole project...
Just Reference your Creature from every Button
var thing:Tamagotchi;
then you can call a public Feed method on them:
thing.Feed();
and then in the Tamagotchi you have a public Feed function
public function Feed()
{
anim.SetTrigger("Feed");
}
Your answer
Follow this Question
Related Questions
How do I animate a 2D sprite? 1 Answer
Playing sprint animation with vertical axis? 0 Answers
Changing number of frames in uvAnimationTileX 0 Answers
Can't animate Sprite correctly 0 Answers
I'm confused with the animator 1 Answer