- Home /
How to load sprites into array Sprite[] in Javascript
For the life of me I can figure this out using Javascript.
I have a multi-sprite collection built from PNG image "spriteatlas.png" in my Resources folder path "Sprites/HD/spriteatlas". There are 41 sprites defined using Unity's multi-sprite maker.
I simply want to load them into a Sprite array at run time but can't get it to work:
var mySprites : Sprite[];
// load all frames in sprite atlas array
mySprites = Resources.LoadAll("Sprites/HD/spriteatlas", typeof(Sprite)) as Sprite[];
This throws no error but the array remains empty.
No matter what I do, the array is always empty. Other versions of my attempts would either load nothing or throw casting errors.
Again, please note that I am doing this in Javascript.
Any advice?
Manny
You should have a png for each sprite you want to make, I don't think you can extract several sprites from a single png with unity.
Answer by Nerevar · May 28, 2015 at 09:16 AM
Hello,
Ok well in c# it is very simple :
Sprite[] album_sprite = Resources.LoadAll<Sprite>("Path");
and in javascript I found a "work-around"
import UnityEngine.UI;
#pragma strict
public var AllSprites : Sprite[];
function Start () {
var imports : Object[] = Resources.LoadAll("icons/" , Sprite);
AllSprites = new Sprite[imports.Length];
for(var i = 0 ; i < AllSprites.Length ; i++){
AllSprites[i] = imports[i];
}
}
Maybe there is a cleaner way to do it but I don't know how.
regards.
Thanks. That's what I had done but was really hoping for cleaner approach like in C#. Thanks for confir$$anonymous$$g.
$$anonymous$$anny
Answer by jepster · Feb 02, 2016 at 05:32 PM
I was trying over and over again to get this to work, and figured out a clean JS approach that's similar to C#:
var mySprites : Sprite[];
mySprites = Resources.LoadAll.<Sprite>("Sprites/HD/spriteatlas");
Notice that you need to put a period before <Sprite>
when using JS.
Your answer
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Strange smearing on texture with unity 4.3.4 1 Answer
Resources.Load(filename) as Sprite is returning null 2 Answers
When i make my character animated, he can only move up, down left and right (2D) (JS) 0 Answers
Changing animation when moving horizontally without flipping sprite 0 Answers