Issue:
By using script to get material property value which is modified by animation, always return still number, without any changes. The unity version I’m using is 2019.1.1.
Steps:
In the sample scene, I’ve add a cube,
Then using animation to control the cube material color.r, from 1.0 - 0.5 - 1.0
Create script, call the value color.r by the following code:
public class ReadAnimatedProperty : MonoBehaviour
{
float _scale;
float _r;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
_r = GetComponent<MeshRenderer>().material.color.r;
Debug.Log("r:" + _r);
}
}
Result:
While playing, the color keeping changing, looping from white to blue to white, which is correct.
In inspector, the material color also keeping changing, which is correct.
In console, the output is always “r:1”, which is incorrect.
In case you want donwload and try, below is the link of my test unity project, download
Working as intended. Animations do not modify the material directly, so looking at the value on the material will show no change. Animations instead use a MaterialPropertyBlock to modifying the properties used per renderer. If you select your mesh and look at the material being modified you’ll see this:
So instead of .material.color (or .material.GetColor("_Color")) should should be doing:
Renderer rend = GetComponent<MeshRenderer>();
MaterialPropertyBlock matBlock = rend.GetPropertyBlock();
Color col = matBlock.GetColor("_Color");
Debug.Log("r:" + col.r);
Some additional notes. You may want to check render.HasPropertyBlock() and / or matBlock.isEmpty before calling matBlock.GetColor() to make sure the renderer has a MaterialPropertyBlock data to look at, and in the case that it does not, use material.GetColor(). Unfortunately there’s no way to know for sure what the value will be for properties that are not being modified by the MaterialPropertyBlock when a property block is being applied. Calling matBlock.GetColor(), or one of the other Get functions, will always return a value of some kind even for values that are not being modified, or may not even exist on the material in question.
The value you get back from matBlock.GetColor() also may not match the value you set if you’re using linear color space as the color returned is the linear space color rather than the gamma space color you’re used to seeing.
Note: This is still happening in Unity 2022, on URP using the SRP batcher. Unfortunately that means that any material modified by animations like this will break batching in URP/SRP Batcher.