Dragon Flea
Dragon Flea

Reputation: 319

Change the animation speed via script?

public class door : MonoBehaviour
{
    void OnTriggerEnter(Collider obj)
    {
        var thedoor = GameObject.FindWithTag("SF_Door");

        Animation anim;
        anim = thedoor.GetComponent<Animation>();
        anim["open"].speed = 10;

        thedoor.GetComponent<Animation>().Play("open");
    }

    void OnTriggerExit(Collider obj)
    {
        var thedoor = GameObject.FindWithTag("SF_Door");
        thedoor.GetComponent< Animation > ().Play("close");
    }
}

I tried to add this part:

Animation anim;
anim = thedoor.GetComponent<Animation>();
anim["open"].speed = 10;

I want to make the door open faster but the code above wasn't changing the speed. Is there any way to do it by script without changing/adding things in the Animator/Animation windows in the editor?

Upvotes: 0

Views: 4973

Answers (2)

joreldraw
joreldraw

Reputation: 1736

Add ".0f" because its a float.

anim["open"].speed = 10.0f;

Upvotes: 1

Fiffe
Fiffe

Reputation: 1256

First of all - you need to stop using Animation. Instead use Mecanim with it's Animator component. Here's a decent introduction video.

The easiest way is to add a new float parameter in your AnimatorController - let's call it speedMultiplier, then in your AnimatorController select the animation that you want to speed up and set it like this:

enter image description here

Now instead of doing anim["open"].speed = ... just do:

Animator anim = thedoor.GetComponent<Animator>();
anim.SetFloat("speedMultiplier", 10);

This way the animation speed will be multiplied by whatever value you set for speedMultiplier.

Upvotes: 2

Related Questions