How to access a Component from another Child when current is Destroyed

My Character(ParentObject) has 2 sprites/skins(dresses or whatever you wanna call it) that you can select from the menu(Children). Those 2 gameObjects(sprites) are stored in a list, whenever I select a skin from the menu, it Instantiate the selected sprite and destroys the current one(they Instantiate inside Character GameObject). Each Sprite has a Animator.

public class Character : MonoBehaviour {
    bool move = false;
    Animator animator;
    
    void Start() {
    
    animator = transform.GetComponentInChildren<Animator>();
    
    }
 
void Update(){
if (Input.GetKeyDown (KeyCode.Space) || Input.GetMouseButtonDown (0)) {
move = true;
						
						}

}

    void FixedUpdate() {
    if (move == true) {
    
    	animator.SetTrigger ("Moved");
    }

When the first sprite is destroyed, I get the error “The Object Type Animator has been destroyed but you are still trying to access it”. I thought that if the first sprite was destroyed, the code (animator = transform.GetComponentInChildren():wink: would get the second Sprite Animator. But isn’t working that way. How do I get the Animator from the second sprite when the first is destroyed.

P.D. : The 2 Sprites have NO script. Character Object has the script Character.

The effect is part of the way the scripting language works. When you store the animator you store a reference to the specific instance of the animator component in memory, not the general animator on the childe object.

To fix you could simply grab a reference to the animator in the update loop

void Update (){
    animator = transform.GetComponentInChildren<Animator>();
    //do other stuff with animator
}

But getting a reference is expensive. This method will cost you in terms of performance.

A better way to do it as follows

  1. First check if the animator component is not null.

  2. If the animator component is null then get a new reference to the animator

    void Update (){
    if (!animator){
    animator = transform.GetComponentInChildren();
    }
    //do other stuff with animator
    }

Its typically a good practice to check if a reference is null every time you refer to a object that might be destroyed.