I'm trying to load a sprite from StreamingAssets. At the end of the import method, the sprite is null again. Why?

I’m trying to add support for mods in my game. The mods should have icons that I can display in some fancy list for the player. Therefore I need to import a single sprite for each mod. But there’s the problem. I just can’t.

The mods are organized in a list of structs, like this:

    public List<Mod> Mods { get; private set; }

And they’re loaded on awake. Their content is pretty simple. A name:

    public string Name { get; private set;}

And an icon.

    public Sprite Icon { get; private set; }

The issue lies with the Icon thingy. I just can’t manage to find out what is happening. The mods are being loaded from the Streaming Assets folder. Any help is appreciated.


Info that may help:

  • The Icon gets successfully assigned during the loading process and is re-setted right after it for some reason.
  • There are no scripts interfering with the loading, this script has been tested in a mostly empty scene, holding only dependencies.
  • Mystery…

The loading code:

public static IEnumerator ImportSprite (string spritePath, Sprite _sprite, FilterMode filterMode, Vector2 pivot)
{
	string finalPath;
	WWW localFile;
	Texture texture;
	Sprite sprite;

	finalPath = "file://" + spritePath;
	localFile = new WWW(finalPath);

	yield return localFile;

	texture = localFile.texture;
	_sprite = Sprite.Create(texture as Texture2D, new Rect(0, 0, texture.width, texture.height), pivot);

	_sprite.texture.filterMode = filterMode;
	//_sprite = sprite;
}

Where exactly are you getting the returned texture? From the parameter _sprite? Is this the returned sprite? If yes, notice that you should use the ref or the out keyword. Otherwise you are doing nothing in your coroutine.

_sprite is no longer the same Sprite that you called this coroutine with.

Sprite.Create returns a new Sprite object.

Pass your Mod into the coroutine, then set the sprite of the Icon directly.

Although you can’t use a ref in a coroutine, you can pass the Mod object entirely and edit its contents.

 public static IEnumerator ImportSprite (string spritePath, Mod _mod, FilterMode filterMode, Vector2 pivot)
 {
     ...
     _mod.Icon = Sprite.Create(texture as Texture2D, new Rect(0, 0, texture.width, texture.height), pivot);
 }