본문 바로가기
개발/C#

유니티 C# 타임라인 Timeline 간단 사용법

by SPNK 2023. 3. 31.
반응형
  • 코드 작성
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;

public class TimelineExample : MonoBehaviour
{
    public GameObject cube;

    private void Start()
    {
        TimelineAsset timelineAsset = ScriptableObject.CreateInstance<TimelineAsset>();

        TrackAsset trackAsset = timelineAsset.CreateTrack<PlayableTrack>(null, "CubeTrack");

        ScriptPlayable<CubeMoverBehaviour> cubeMoverPlayable =
            ScriptPlayable<CubeMoverBehaviour>.Create(trackAsset);

        CubeMoverBehaviour cubeMoverBehaviour = cubeMoverPlayable.GetBehaviour();
        cubeMoverBehaviour.cube = cube;

        timelineAsset.duration = 5f;

        TimelinePlayable timelinePlayable = TimelinePlayable.Create(PlayOnAwake: false);
        timelinePlayable.SetGraph(CreatePlayableGraph(timelineAsset));

        PlayableDirector playableDirector = gameObject.AddComponent<PlayableDirector>();
        playableDirector.playableAsset = timelinePlayable;
    }

    private PlayableGraph CreatePlayableGraph(TimelineAsset timelineAsset)
    {
        PlayableGraph playableGraph = PlayableGraph.Create();
        ScriptPlayable<TimelinePlayableBehaviour> timelinePlayable =
            ScriptPlayable<TimelinePlayableBehaviour>.Create(playableGraph);

        timelinePlayable.GetBehaviour().SetDuration(timelineAsset.duration);

        playableGraph.Play();

        return playableGraph;
    }
}

public class CubeMoverBehaviour : PlayableBehaviour
{
    public GameObject cube;
    public Vector3 startPosition;
    public Vector3 endPosition;

    public override void OnBehaviourPlay(Playable playable, FrameData info)
    {
        startPosition = cube.transform.position;
        endPosition = cube.transform.position + Vector3.right * 5f;
    }

    public override void ProcessFrame(Playable playable, FrameData info, object playerData)
    {
        float time = (float)playable.GetTime();

        cube.transform.position = Vector3.Lerp(startPosition, endPosition, time / (float)playable.GetDuration());
    }
}
반응형

댓글