Standort
Standort

Reputation: 11

Unity: Resources.Load<Sprite> returns null

Currently I'm working on a card game, I call the cards champions, they have id, name, cost and sprite. I use the database script to add each card. Here is where I call the function:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChampionDatabase : MonoBehaviour
{

    public static List<Champion> championList = new List<Champion>();

    private void Awake()
    {
        
        championList.Add(new Champion(0, "Garen",1, Resources.Load<Sprite>("Garen")));
        championList.Add(new Champion(1, "Katarina", 2, Resources.Load<Sprite>("Katarina")));
        Debug.Log(Resources.Load<Sprite>("Garen"));//this returns null 
    }
}

This is my champion script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Champion 
{

    public int id;
    public string championName;
    public int cost;
    public Sprite spriteImage;

  
    public Champion()
    {

    }

    public Champion(int Id, string Name, int Cost, Sprite SpriteImg  )
    {
        id = Id;
        championName = Name;
        cost = Cost;
        spriteImage = SpriteImg;


    }

}

my resource folder

Upvotes: 0

Views: 959

Answers (1)

derHugo
derHugo

Reputation: 90580

In order to load these as sprites they also need to be set as Sprites.

Select them and in the Inspector (the Texture Import Settings) change the TextureType from Default to Sprite (2D and UI) and hit Apply


From Unity Best Practices -> Resources

Don't use it.

instead make sure to

and then in your class rather have a serialized field

public List<Champion> championList = new List<Champion>();

and simply configure these and reference your sprites via drag & drop in the Inspector!


IF you then really need it to be static either copy it over once

[SerializeField] private List<Champion> _championList = new List<Champion>();

public static List<Champion> championList = new List<Champion>();

private void Awake ()
{
    championList = _championList;
}

or look into "Singleton Pattern".

Upvotes: 0

Related Questions