- Home /
How to make Image preloader script
Hello, i know this could be a "noob" question, that's because i'm newbie using Unity yet haha.
I am creating a project which uses all images inside an array[] to change a specific image; I mean the image will change to another according some frames per second, the problem is that when it happens the project freezes for about 2-4 seconds, i was thinking about creating an Image preloading script, but i certainly haven't idea about how, i'd love to -please-, receive some help about how could i start doing this.
EDIT: well, i wasn't clear at all, i think, so this is what i have for now:
This script should get all images from a specific folder and put them inside the Frames array, then a Main Sprite will be changing continuously according the FPS and exactly in the array order. Bassicaly it's a "Gif player" that's why the script is called Giffier.
when the player kills the enemy, the FolderName is changed to the next's enemy's folder name but when that happens, the game freezes completely for about 2-4 seconds as I said before, i was thinking so much time about it and noticed that it could be a performance problem due to the Frames[] array content change, but also noticed that it doesn't happens when previusly killed enemies are the same than the current (i.e., Player kills EnemyA and EnemyB, if the next enemy is EnemyA or EnemyB the game doesn't freezes but if a new EnemyC spawns, the game freezes)
public class Giffier : MonoBehaviour
{
public Sprite[] Frames;
public float FramesPerSecond = 30f;
public string FolderName; // Current Enemy's folder
void Start ()
{
GetSprites ();
}
void Update ()
{
GetSprites ();
// Get index of frame.
int index = (int)(Time.time * FramesPerSecond) % Frames.Length;
// Check if the array isn't null.
if (Frames [index] != null) {
// get & update sprite.
this.gameObject.GetComponent<SpriteRenderer> ().sprite = Frames [index];
}
}
public void GetSprites ()
{
for (int i = 1; i < Frames.Length; i++) {
Frames [i] = (Sprite)AssetDatabase.LoadAssetAtPath ("Assets/Graphics/Enemies/" + FolderName + "/Frame-" + i + ".png", typeof(Sprite));
}
}
}
by the way; the Frames[] size is also changed when the enemy is killed with a little function:
//"Gif" is the Giffier script
void Update(){
NextStage();
}
public void NextStage()
{
if (CurrentEnemyHP <= 0f)
{
CurrentEnemyID = Random.Range (1, 151);
Gif.FolderName = EnemyDB.GetEnemy (CurrentEnemyID).Name;
Gif.Frames = new Sprite[EnemyDB.GetEnemy (CurrentEnemyID).FramesQtty];
}
}
Please, edit your question and provide the code causing the freeze. If the images are referenced in the array, they are loaded when the game starts.
You may also want to take a look at atlas (a.k.a spritesheets) https://docs.unity3d.com/$$anonymous$$anual/class-SpriteAtlas.html
Hey, thank you for helping me, i edited the topic and i think it's better now, any tip? i'll read about atlas too it will be useful