Search code examples
c#unity-game-enginedesign-patterns

How to assign a specific icon to a specific weapon?


Each weapon in the game does have an icon that will be shown on screen when the weapon is picked up.

The weapons are implement as different classes all based on the same base abstract class.

What I'm trying to sketch up is how to define such relationship in the editor, specifically, I want to be able to change a weapon's icon by drag'n'drop a texture on some object in the inspector.

What I'm not looking for:

  • the use of enumerations to declare such relationship
  • not declaring a direct reference to a texture asset, i.e. a path.

How would you achieve that?


Solution

  • You will want to declare a Sprite reference in a MonoBehaviour or ScriptableObject to be assigned in the editor/inspector.

    [SerializeField] private Sprite icon;
    
    public Sprite GetIcon()
    {
        return icon;
    }
    

    MonoBehaviour

    Using MonoBehaviour is a common method to store data on objects where the data should be assigned in the editor/inspector. Those objects can be prefabbed to exist as assets. This assumes your weapons exist as game objects.

    • Declare the Sprite inside a MonoBehaviour that is common to all weapons (e.g., a common Weapon.cs, or the base class that you mentioned).
    • Then you can create objects (and prefabs of those objects) with the MonoBehaviour attached and assign icons in the inspector.

    ScriptableObject

    You can alternatively use a ScriptableObject, which can be thought of as "data as assets".

    • Create the ScriptableObject "template" called WeaponData and declare the Sprite inside.
    • Create 1 WeaponData asset for each weapon and assign icons to those assets in the inspector.
    • Have your game systems reference WeaponData to get the icon Sprite.

    Scriptable Object Unity Docs