PrimeTween Documentation

repository·main·Indexed 23 days ago

https://github.com/kyrylokuzyk/primetween

A high-performance, allocation-free animation library for Unity designed for strictly typed script-based animations of user-interfaces and world-space objects. PrimeTween supports a wide range of components including Transform, Rect Transform, Sprite Renderer, Audio Source, and Light, as well as generic types like float, Color, and Vector. It features Inspector integration via TweenSettings, parametric easing functions, and speed-based animations.

Tokens
9.1K
Snippets
26
Records
43
Agent score
83%

What's inside PrimeTween

  1. How Sequences work

    main

    A Sequence is a container for grouping tweens, callbacks, and other sequences. It allows you to orchestrate complex animations that can overlap, run sequentially, or run in parallel.

    Sequence Composition Methods:

    • Insert(float atTime, Tween/Sequence animation): Places an animation at a specific time, overlapping with existing animations. This may increase the total sequence duration.
    • Chain(Tween/Sequence animation): Places an animation after all previously added animations. Chained animations run sequentially.
    • Group(Tween/Sequence animation): Groups an animation with the preceding animation in the sequence. Grouped animations start at the same time and run in parallel.

    To apply cycles to a Sequence, use Sequence.Create(cycles: numCycles, cycleMode: CycleMode.Yoyo).

    Sequence.Create(cycles: 10, CycleMode.Yoyo)
        // PositionX and Scale tweens are 'grouped', so they will run in parallel
        .Group(Tween.PositionX(transform, endValue: 10f, duration: 1.5f))
        .Group(Tween.Scale(transform, endValue: 2f, duration: 0.5f, startDelay: 1))
        // Rotation tween is 'chained' so it will start when both previous tweens are finished (after 1.5 seconds)
        .Chain(Tween.Rotation(transform, endValue: new Vector3(0f, 0f, 45f), duration: 1f)) 
        .ChainDelay(1)
        .ChainCallback(() => Debug.Log("Sequence cycle completed"))
        // Insert color animation at time of '0.5' seconds
        // Inserted animations overlap with other animations in the sequence
        .Insert(atTime: 0.5f, Tween.Color(image, Color.red, duration: 0.5f));
  2. Configure tween cycles and modes

    main

    You can repeat animations by passing cycles and cycleMode to a Tween method. Setting cycles to -1 creates an infinite loop.

    CycleMode options:

    • Restart (default): Restarts the tween from the beginning.
    • Yoyo: Animates forth and back (easing is the same on the backward cycle).
    • Incremental: Increments the endValue by the difference between startValue and endValue at the end of each cycle.
    • Rewind: Rewinds the tween as if time was reversed (easing is reversed on the backward cycle).

    Methods for managing cycles:

    • SetRemainingCycles(int cycles): Sets the number of remaining cycles.
    • SetRemainingCycles(bool stopAtEndValue): If true, stops the animation when it reaches endValue (for Yoyo/Rewind). If false, stops at startValue.
    Tween.PositionY(transform, endValue: 10, duration: 0.5f, cycles: 2, cycleMode: CycleMode.Yoyo);
  3. Use TweenAnimation for Inspector-based authoring (PRO)

    main

    The TweenAnimation class (available in PrimeTween PRO) allows you to create and tweak complex animations directly in the Unity Inspector without writing code.

    Key Features

    • Inspector Workflow: Add multiple animations using the '+' button. Chain, delay, or insert animations at specific times.
    • Edit Mode Preview: Use the preview controls at the top of the Inspector to test animations without entering Play Mode.
    • Trigger(): Plays the animation. For simple/infinite animations, it plays from the start; for reversible animations, it changes direction.
    • state { get; set; }: Manages the logical state.
      • Simple: true if playing.
      • Infinite: true if playing and not interrupted.
      • Reversible: true if moving forward or at the end. Setting this changes direction.
    • isReversible: A boolean property useful for toggle animations (e.g., open/close). Setting state = true plays forward, state = false reverses.
    // Add TweenAnimation to your script, then set the animation up in the Inspector.
    [SerializeField] TweenAnimation doorAnimation = new();
    
    void Update() {
        if (Input.GetKeyDown(KeyCode.Space)) {
            // Play the animation in response to gameplay events.
            doorAnimation.Trigger();
    
            // Or set the state directly.
            doorAnimation.state = true;
        }
    }
  4. Upgrade DOTween from versions older than 1.2.000

    main

    If you are upgrading from a version of DOTween older than 1.2.000 (or DOTween Pro older than 1.0.000), follow these steps to avoid project errors:

    1. Import the new version into the same folder as the previous version, overwriting existing files. (Note: Errors may appear during this process).
    2. Close and reopen Unity and your project. This step is required to prevent significant issues.
    3. Open the DOTween Utility Panel via Tools > Demigiant > DOTween Utility Panel.
    4. Click the Setup DOTween... button to run the upgrade setup.
    5. In the Add/Remove Modules panel, activate or deactivate the necessary Modules for Unity systems or external assets (Pro version only).
  5. Migrate from DOTween to PrimeTween

    main

    If you are moving from DOTween to PrimeTween, use the following mapping for common operations:

    Virtual and Custom Tweens

    • DOVirtual.DelayedCall() $\rightarrow$ Tween.Delay()
    • DOTween.To() $\rightarrow$ Tween.Custom()
    • DOVirtual.Vector3() $\rightarrow$ Tween.Custom()

    Sequences

    • DOTween.Sequence() $\rightarrow$ Sequence.Create()
    • sequence.Join() $\rightarrow$ sequence.Group()
    • sequence.Append() $\rightarrow$ sequence.Chain()
    • sequence.AppendCallback() $\rightarrow$ sequence.ChainCallback()
    • seq.Insert(1.5f, trans.DOMoveX(...)) $\rightarrow$ seq.Insert(1.5f, Tween.PositionX(trans, ...)) or use seq.Group(Tween.PositionX(..., startDelay: 1.5f)) before the first Chain() operation.
    • seq.InsertCallback(1f, callback) $\rightarrow$ seq.InsertCallback(1f, callback)

    Lifecycle and Control

    • DOTween.Kill(target, false) $\rightarrow$ Tween.StopAll(onTarget: target)
    • DOTween.Kill(target, true) $\rightarrow$ Tween.CompleteAll(onTarget: target)

    Coroutines and Async/Await

    • yield return tween.WaitForCompletion() $\rightarrow$ yield return tween.ToYieldInstruction()
    • yield return sequence.WaitForCompletion() $\rightarrow$ yield return sequence.ToYieldInstruction()
    • await tween.AsyncWaitForCompletion() $\rightarrow$ await tween (PrimeTween supports await directly on tweens and sequences, even on WebGL)

    Transform and Property Tweens

    • transform.DOMoveX(to, 1).From(from) $\rightarrow$ Tween.PositionX(transform, from, to, 1)
    • trans.DOMove(pos, speed).SetSpeedBased() $\rightarrow$ Tween.PositionAtSpeed(trans, pos, speed)
    • tween.SetDelay(1f).OnStart(callback) $\rightarrow$ Tween.Delay(1, callback).Chain(tween)
    • sequence.OnStart(callback) $\rightarrow$ sequence.ChainCallback(callback) (at the beginning of the sequence)

    Other Mappings

    • tween.SetId() $\rightarrow$ See GitHub Discussion
    • target.DOBlendable___(...) $\rightarrow$ Tween.___Additive(target, ...) (experimental)
  6. Avoid allocations in callbacks using target parameters

    main

    To prevent heap allocations when using delegates (like OnComplete or OnUpdate), avoid using anonymous lambdas that capture this. Instead, pass the object instance as the target parameter and use the target argument within the callback.

    Incorrect (Allocates): OnComplete(() => SomeMethod())

    Correct (Zero Allocation): OnComplete(target: this, target => target.SomeMethod())

  7. Debug running tweens with PrimeTweenManager

    main

    To inspect currently running tweens and their properties, select the PrimeTweenManager object located under the DontDestroyOnLoad foldout in the Unity Hierarchy.

    If a tween's target is a UnityEngine.Object, you can click the Unity Target field in the Inspector to quickly locate it in the Hierarchy. For optimal debugging, it is recommended to supply the target even for optional parameters like Tween.Delay() and Tween.Custom().

  8. Get started with DOTween

    main

    To begin using DOTween in your Unity project:

    1. Setup Modules: After importing, open the DOTween Utility Panel (Tools > Demigiant > DOTween Utility Panel) and click Setup DOTween... to configure your modules. You can also use the Preferences Tab in this panel to set default settings.
    2. Add Namespace: Include the following using directive in every C# class where you intend to use DOTween functionality:
    using DG.Tweening;
  9. Animate forward and backward using direction

    main

    PrimeTween does not support changing the direction of a running tween. To play an animation forward or backward (e.g., opening/closing a UI window), you should start a new tween in the desired direction.

    New tweens will automatically overwrite any previously running tweens on the same target. If you are calling tweens every frame, you should manually stop the previous tween using tween.Stop() or Tween.StopAll(onTarget: target) to avoid excessive duplication.

    [SerializeField] RectTransform window;
    
    public void SetWindowOpened(bool isOpened) {
        // The new tween seamlessly starts from the current position and overwrites the old one
        Tween.UIAnchoredPositionY(window, endValue: isOpened ? 0 : -500, duration: 0.5f);
    }