Search Unity

Question How to change rig weight at runtime?

Discussion in 'Animation Rigging' started by dschu, Apr 23, 2021.

  1. dschu

    dschu

    Joined:
    Dec 10, 2019
    Posts:
    5
    Environment
    • Unity 2020.3.5f1
    • Animation Rigging 1.0.3
    Description
    I have set up a humanoid avatar with some basic movement animations and added a `Rig Builder` component to it. I added an empty child for the `Head Rig` and added two `Multi Aim Constraints` as its children. One for the head, one for the upper body. Then, I've added the `Head Rig` to the Rig Builders `Rig Layers`. So far so good, everything is working and the head rig is influencing the body parts very well.

    However, the jump animation looks weird when being influenced by that `Head Rig`, so I've added two `Animation Events` that are called on the beginning & the end of the jump. Those functions should set thei `Head Rig` weight to 0 when the jump starts and to 1 once the jump has ended.

    Inside my PlayerController, I've added the following code to accomplish that:
    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.Animations.Rigging;
    6.  
    7. public class PlayerController : MonoBehaviour
    8. {
    9.     public RigBuilder rigBuilder;
    10.     public Rig headRig;
    11.  
    12.  
    13.     [...]
    14.  
    15.     void OnJumpStart()
    16.     {
    17.         Debug.Log("Jump Start" + headRig.weight); // Output: Jump Start1
    18.         headRig.weight = 0f;
    19.     }
    20.     void OnJumpEnd()
    21.     {
    22.         Debug.Log("Jump End" + headRig.weight); // Output: Jump End1
    23.         headRig.weight = 1f;
    24.     }
    25. }
    26.  
    27.  
    But the weight is always 1. When I use the slider on the `Head Rig`, it's working as intended.

    Any thoughts?

    Thank you!
     
  2. Yandalf

    Yandalf

    Joined:
    Feb 11, 2014
    Posts:
    491
    Weight values always need to be set during Update or Coroutine calls, apparently.
    I'm not entirely sure why this is, but it might have something to do with the fact Animation Rigging Constraints are multithreaded code and thus needs to strictly control when and where data changes.
     
    AqueuseAkaLLO and dschu like this.
  3. archangel007

    archangel007

    Joined:
    Oct 9, 2020
    Posts:
    5
    Just came cross this issue myself, seems rigging constraints using "JOB" system, so may not be able to directly modify the weight value, use use Update and Coroutine as Yandalf pointed out, here is this way to do:

    IEnumerator UpdateRigWeight(float start, float end)
    {
    float elapsedTime = 0;

    while (elapsedTime < _transitionTime)
    {
    _rig.weight = Mathf.Lerp(start, end, (elapsedTime / _transitionTime));

    elapsedTime += Time.deltaTime;
    yield return null;
    }
    }
     
    Last edited: Jul 14, 2023