#Managing a sprite with multiple visual states

1 messages · Page 1 of 1 (latest)

wanton sleet
#

I have a collectible object that can spawn as one of four different 'types' with different sprites. I want to use a single Prefab object to represent all four. What's a good way to load the correct sprite when an instance of the prefab is instantiated?

I could use an Animator with four one-keyframe animations, but since the sprite isn't actually animating at all this seems like it would be a waste of resources.

somber horizon
#

Hi there! I think the best approach here is to keep it simple. Just have the references for the sprites you want and, depending on which one it is, assign it. Something like this:

[SerializableField] private Image imageReference;
[SerializableField] private Sprite collectibleA;
[SerializableField] private Sprite collectibleB;
[SerializableField] private Sprite collectibleC;
[SerializableField] private Sprite collectibleD;

public void SetSprite(CollectibleType type){
if(type == CollectibleType.A)
imageReference.sprite = collectibleA;
else if(type == CollectibleType.B)
imageReference.sprite = collectibleB;
else if(type == CollectibleType.C)
imageReference.sprite = collectibleC;
else (type == CollectibleType.D)
imageReference.sprite = collectibleD;
}

#

If you want something more generic, you could save the sprites in a folder called Resources, and do something like this:

[SerializableField] private Image imageReference;

public void SetSprite(CollectibleType type){
imageReference.sprite = Resources.Load<Sprite>("CollectibleSprite_"+type.ToString());
}

#

In this case, you should have the sprites in Resources with that naming convention (CollectibleType_[nameOfType]).