How do I assign a variable the proper sprite in the script? (C#)

Hello,

I have a sprite in a folder called “Sprites” in the Assets folder. I want a variable in my script to be assigned that sprite on start, however, I’ve run into a problem. Here’s my current script, how do I fix it?

 void Start()
 {
        nameOfSprite = Resources.Load("NameOfSprite", typeof (Sprite)) as Sprite;
} //this is the broken part, for some reason it won't load the sprite.

void Update()
{
    GameObject gameObject= GameObject.Find("GameObject");
    gameObject.GetComponent<SpriteRenderer>().sprite = nameOfSprite;
    //there should be no problems with this part, I've used it in the past and it worked just fine.
}

I’ve used placeholder names, hope you don’t mind.

Thanks.

The resources class only loads files from the Resources folder in your project (which you need to create and name yourself). You cannot have it load stuff from wherever you want (random “Sprites” folder and such). Move your sprites folder, or its contents, to the Resources folder and then try again. If loading from resources is not essential to your game you could also simply have a public Sprite field in your class, assign it through the inspector and then use it, wherever you want in you class.

Here’s the documentation on how to use the resources class and its methods

Hope this helps!