Cannot Change Animator Layer Settings in Script

I have some code that creates the Animator Controller from a scriptable object and it has been working great so far. I’ve done just about everything from states, sub-states, blend trees, transitions, etc. Now, I’m trying to add a new layer and set the layer’s properties. The layer itself is created fine and so are the animator states inside the layer. However, when I try to change layer settings such as avatarMask and defaultWeight, they won’t take.

When I breakpoint debug, the value I’m trying to assign is valid, but after stepping over the assignment code, the layer setting value is unchanged. Here is the code I am using:

            int layerIndex = _controller.layers.Length;
            _controller.AddLayer(LAYER_TURNING);
            _controller.layers[layerIndex].avatarMask = locomotionAnimations.turningLayer.avatarMask;
            _controller.layers[layerIndex].defaultWeight = locomotionAnimations.turningLayer.maskWeight;

Any ideas why these layer settings cannot be set like this?

I’m using Unity 2021.3.27f1.

I finally found the solution in this thread:

I know this is an old topic, but I figured out what’s going on and how to get around it.
AnimatorController.layers actually gets an array filled with copies of the layers on the controller.

If you set it back like this:

var layers = controller.layers;
layers[0].name = "NewLayerName";
controller.layers = layers;

It works.

I will note, though, that if you’re following a pattern like in the OP, you should just set all the fields in the layer before you add it to the controller (as shown in the original solution). That would be more efficient than working around the issue like this. You should only use the method in this post if you’re changing a layer that existed previously.