Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How to assign assets to non-monobehaviour classes?

Discussion in 'Scripting' started by ShiftyGames, Jan 9, 2022.

  1. ShiftyGames

    ShiftyGames

    Joined:
    Sep 10, 2018
    Posts:
    16
    I want to use a non-monobehaviour class that has a Sprite field. As it can't be attached to a game object, I can't expose the Sprite field in the editor and therefore can't assign a Sprite.

    I thought about creating an Assets prefab that is instantiated briefly when the game starts and loads all the sprites into public static fields so I can access them anywhere with
    Assets.Sprites.someSprite
    but this feels messy.

    I'm also aware of
    Resources.Load<T>("someSprite");
    but this isn't recommended for a few reasons.

    Is there a clean way of doing this?
     
  2. _geo__

    _geo__

    Joined:
    Feb 26, 2014
    Posts:
    1,115
    Maybe Addressables might be a good fit for you. They are the recommended solution for loading assets at runtime.
    https://docs.unity3d.com/Manual/com.unity.addressables.html
    https://docs.unity3d.com/Packages/com.unity.addressables@1.19/manual/index.html

    If all you want is a convenient way to reference sprites then you could list (List<Sprite>) them in a ScriptableObject object and then pass a reference to that SO around. Of course you would have to either load or hardwire the SO somewhere. The advantage would be that all you need is a single ref to that SO.
     
    ShiftyGames likes this.
  3. adehm

    adehm

    Joined:
    May 3, 2017
    Posts:
    369
    The simplest way to get you started would be to make a class that loaded individual sprites like below.

    Code (CSharp):
    1. using UnityEngine;
    2. public class ASpriteAnimation
    3. {
    4.     Sprite[] sprites= new Sprite[3];
    5.     public class LoadSprites()
    6.     {
    7.         sprites[0] = Resources.Load<Sprite>("SpritePath/Sprite0);
    8.         sprites[1] = Resources.Load<Sprite>("SpritePath/Sprite1);
    9.         sprites[2] = Resources.Load<Sprite>("SpritePath/Sprite2);
    10.    }
    11. }
     
    Last edited: Jan 9, 2022
    ShiftyGames likes this.