Version: 5.4
Объекты с множеством двигающихся частей
Animator Controllers (контроллеры аниматоров)

Использование событий в анимации

Details

Сила анимационных клипов может быть увеличена с помощью событий анимации (Animation Events), которые позволяют вам вызывать функции в скриптах объекта в указанных точках временной шкалы клипа.

Функция, вызываемая событием анимации может дополнительно принимать один параметр. Параметр может быть числом с плавающей точкой, строкой, целым числом, ссылкой на объект или AnimationEvent объектом. Объект AnimationEvent имеет переменные-члены, позволяющие передать число с плавающей точкой, строку, целое число, ссылку на объект, которые будут переданы в функцию все сразу, наряду с другой информацией о событии, которое осуществило вызов функции.

// This C# function can be called by an Animation Event
public void PrintFloat (float theValue) {
    Debug.Log ("PrintFloat is called with a value of " + theValue);
}


Вы можете добавить событие анимации к клипу в текущей позиции воспроизведения, нажав Кнопку Event или в любой момент анимации, дважды щелкнув на строке событий (Event Line) в точке, где вы хотите добавить триггер события. После добавления, событие может быть перемещено с помощью мыши. Вы можете удалить событие, выбрав его и нажав Delete, или щелкнув правой кнопкой мыши на нем и выбрав Delete Event из контекстного меню.

Animation Events are shown in the Event Line. Add a new Animation Event by double-clicking the Event Line or by using the Event button.
Animation Events are shown in the Event Line. Add a new Animation Event by double-clicking the Event Line or by using the Event button.

Когда вы добавляете событие, показывается диалоговое окно для указания имени функции и значения параметра, который вы хотите передать ей.

The Animation Event popup dialog lets you specify which function to call with which parameter value.
The Animation Event popup dialog lets you specify which function to call with which parameter value.

Добавленные к клипу события в строке событий показываются в виде маркеров. Удержание мыши над маркером показывает подсказку с именем функции и значением параметра.

Holding the mouse cursor over an Animation Event marker will show which function it calls as well as the parameter value.
Holding the mouse cursor over an Animation Event marker will show which function it calls as well as the parameter value.

Пример

This example is very simple. Add a small script with just a simple function, PrintEvent(), that prints a debug message including a string and the time:

// This C# function can be called by an Animation Event
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public void PrintEvent(string s) {
        Debug.Log("PrintEvent: " + s + " called at: " + Time.time);
    }
}

In Unity create a Cube object and add the ExampleClass script code. Select the cube and then open the Animation window. Set a Position curve for the x coordinate.

Animation window
Animation window

Next set the animation for the x coordinate to increase to around 0.4 and back to zero over 1 second. Next create an animation event at approximately 0.8 seconds. Press the Play button and the cube animates forwards and backwards along the x-axis. The event message is displayed in the console every 1 second at the 0.8 second time. This example shows a simple way to add animation events to a simple GameObject.

Объекты с множеством двигающихся частей
Animator Controllers (контроллеры аниматоров)