Change component material on child objects (Anima2d)

Hi this is my first unity project so bear with me.

I’m using anima2d in my game and skeletal animation on my main character. When he is hit I want him to turn white. So I think the best way of doing this (I could be wrong) would be to have a script on the parent holder object for my character which loops through all the children and apply a material to anima2d’s Sprite Mesh Instance component.

Here’s my code:

public Material white;

void Start () {
	foreach (Transform child in transform) {
	    	child.GetComponent<Anima2D.SpriteMeshInstance>().sharedMaterial = white;

}

But i get the error: Object reference not set to an instance of an object

GetComponent<Anima2D.SpriteMeshInstance>().sharedMaterial = white;

The above line of code works if I attach a script to the object I want white.
But I don’t think it’s efficient to go through each sprite that make up the bones and apply this, am I right in thinking it’s best to use a loop?

Thanks in advance!

try changing that line of code to this and tell me if it works.

child.GetComponent<Anima2D.SpriteMeshInstance>()?.sharedMaterial = white;

Hi thanks for your help with this. I managed to get it working by creating a “spritemeshs” game object and putting everything I wanted to turn white in there. Then just added the script to spritemeshs game object.

It was like you said, it wasn’t working because some of the children didn’t have that component.

Thanks