How do I smoothly shift between Layer Weights

I’m trying to shift between my character’s default layer to another layer where his arms are masked smoothly so it looks like putting them out to hold a gun.

public bool gun;

	void Update () {
		if (gun) {
			animator.SetLayerWeight (GunLayer, Mathf.Lerp (0.0f, 1.0f, Time.time));
		}
	}

Whenever gun is true I want the Layer Weight to lerp from 0 to 1 but it instantly goes to 1 if it is in a if condition block. When I take it out the if condition block it works perfectly but for my game I need to use an if condition.

For anyone still reading this.

I just want to add that using “Mathf.SmoothDamp” can result in an even smoother transition since you have more control over how that transition behaves for ex: how long is it supposed to last

Down here is an example of how i used it. I suggest you refer to the doc here for more info


var m_currentLayerWeight = _playerAnimator.GetLayerWeight(1);
    m_currentLayerWeight =Mathf.SmoothDamp(m_currentLayerWeight, IsArmed ? 1 : 0, ref _currentLayerWeightVelocity, animTransSmoothTime);
    _playerAnimator.SetLayerWeight(1,m_currentLayerWeight);

PS : in this example we fade in & out depending on if the player IsArmed or not

You could just use a variable for saving the current layer weight:

Fade Out:

currentWeight =
Mathf.Lerp(currentWeight,0.0f,Time.deltaTime);
anim.SetLayerWeight(1,
currentWeight);

Fade In:

currentWeight =
Mathf.Lerp(currentWeight,1.0f,Time.deltaTime);
anim.SetLayerWeight(1,
currentWeight);