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!
maybe because not all of the childs have a Anima2d.spritemeshinstance? check if all the childs have that component.
Hi thanks for your reply! No they don't all have that component. Is it possible to only apply that code to game objects with the Anima2d.spritemeshinstance component?
Thanks for your help
Answer by xxmariofer · Mar 11, 2019 at 02:37 PM
try changing that line of code to this and tell me if it works.
child.GetComponent<Anima2D.SpriteMeshInstance>()?.sharedMaterial = white;
Answer by RealMcCoyGames · Mar 11, 2019 at 03:56 PM
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
you were trying to access a component on childs that didnt have that component, for future project or similar issues yoou can just compare if the component is null or use the "?" operator as in my previous answer that will save you extra work.
Your answer
Follow this Question
Related Questions
Is there no way to inherit children's components for validation/checking purposes? 1 Answer
Drop down menu for public variables on a component in the inspector. 0 Answers
Creating Modular Firing Mechanism 1 Answer
Set Component property using a var 0 Answers
How to re-enable multiple components in one script 0 Answers