2D Toolkit Forum

2D Toolkit => Support => Topic started by: spitfire7 on March 20, 2013, 03:29:51 pm

Title: Trigger Animation
Post by: spitfire7 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");
}
}

}
Title: Re: Trigger Animation
Post by: unikronsoftware 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?
Title: Re: Trigger Animation
Post by: spitfire7 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?
Title: Re: Trigger Animation
Post by: unikronsoftware 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.
}
}