Changing sprite of child object changes the parent object's sprite instead

So I am setting up an inventory system and I have slots which hold objects. However, whenever I use the following code, the image of the parent(slot) changes to the desired sprite instead of the image of the child(item):

GetComponentInChildren().sprite = itemHeld.Sprite;

Any ideas on what I might be doing wrong?

Hi, GetComponentInChildren() returns the component of the GameObject itself too (see documentation).

I guess it returns the one from the GameObject before the one from the child objects (and it won’t return the one from inactive child gameobjects). This could explain why your code changes the one from the parent object and not the child.

To access the child item’s component: you can use transform.GetChild( childIndexNumber ).GetComponent()

Without more detail as to the hierarchy & code we can only guess, but assuming you want to change the first child, try executing this code in the script on the parent;

this.gameObject.transform.GetChild(0).GetComponent().sprite = itemHeld.Sprite;


this.gameObject.transform.GetChild(0).GetComponentInChildren().sprite = itemHeld.Sprite;

That’s untested as i dont know unityscript or your scene. But hopefully you get the idea :wink: