Hello Guest

Author Topic: Trigger Animation  (Read 4371 times)

spitfire7

  • Newbie
  • *
  • Posts: 2
    • View Profile
Trigger Animation
« on: March 20, 2013, 03:29:51 pm »
Basically I want to trigger an animation (tk2d Animated Sprite) when the character controller passes through a box collider and I do not know how to do this. I've been struggling for hours since I am very much new to scripting. I would be really grateful if someone could help me out. Thank you in advance.

This is what I have done so far...

Code: [Select]
using UnityEngine;
using System.Collections;

public class TriggerAnimation : MonoBehaviour
{
tk2dAnimatedSprite animSprite;

// Use this for initialization
    void Start () {
        animSprite = GetComponent<tk2dAnimatedSprite>();
    }

void  OnTriggerEnter ( Collider other  ){
if(other.transform.tag=="Player")
{
animSprite.Play("dialogue1");
}
}

}

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: Trigger Animation
« Reply #1 on: March 20, 2013, 03:34:24 pm »
The script looks alright, but is it actually getting into OnTriggerEnter? Debug.Log("...") something in there to make sure it is doing it.

Also, I take it your player is tagged with "Player" and your animated sprite has a collider set to "trigger" on it?

spitfire7

  • Newbie
  • *
  • Posts: 2
    • View Profile
Re: Trigger Animation
« Reply #2 on: March 21, 2013, 02:37:14 pm »
Why is it that when I tick mark "create collider", the collider positions itself at "100000" in the Z axis and when I move it and hit the play button, the collider disappears. I also tried adding a box collider through component>physiscs but I am facing the same problem.

Update: I created a cube and parented it to the animated sprite. It triggers but gives me this error:

NullReferenceException: Object reference not set to an instance of an object
TriggerAnimation.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/TriggerAnimation.cs:17)

Update: I set the collider type to "unset", re-added the box collider and that fixed it but every time I pass the collider it plays the animation. It is set to "play automatically" and wrap mode "once". I want the animated sprite to play once and destroy/hide/deactivate itself. Could you please tell me how?
« Last Edit: March 21, 2013, 04:26:33 pm by spitfire7 »

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: Trigger Animation
« Reply #3 on: March 21, 2013, 07:10:26 pm »
You should add a behaviour to do this. It'll be really simple, something like this will do the job.

Code: [Select]
using UnityEngine;

class DestroyOnCompleteAnimation {
void Start() {
tk2dAnimatedSprite anim = GetComponent<tk2dAnimatedSprite>();
anim.animationCompleteDelegate = OnAnimationComplete;
}

void OnAnimationComplete(tk2dAnimatedSprite sprite, int clipId) {
Destroy(gameObject);
                // do what you want to here.
}
}