Unity3D: loading and using sprite atlas from Resources

Trabla: Unity3D: loading and using sprite atlas from Resources


Unity3D load sprite atlas from Resources - tutorial 1



Solving:


1. Create sprite atlas ( .png file images, background transparent )


Unity3D load sprite atlas from Resources - tutorial 2


Unity3D load sprite atlas from Resources - tutorial 3
"sprite-atlas.png" File


2. Create new unity2D project

Unity3D load sprite atlas from Resources - tutorial 4


3. Create folder "Resources" in folder "Assets"
and drag-n-drop sprite atlas file into folder "Resources"

Unity3D load sprite atlas from Resources - tutorial 5



4. Select sprite atlas file - set "Sprite Mode" -> "Multiple" + click "Apply"

Unity3D load sprite atlas from Resources - tutorial 6



5. Click "Sprite Editor" - slice sprite in automatic mode - will create separate sprites.

Unity3D load sprite atlas from Resources - tutorial 7

Unity3D load sprite atlas from Resources - tutorial 8
Slice Result



6. Create following UI structure:
Panel
- Text
- Button
- Image

Unity3D load sprite atlas from Resources - tutorial 9

Unity3D load sprite atlas from Resources - tutorial 10



7. Create new C# script , name it "SpriteAtlasController"  and add as component to "Panel"

8. Copy following code into "SpriteAtlasController.cs"

using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Add this directive for UI Components e.g. Text, Button etc.
using System.Collections.Generic; 


public class SpriteAtlasController : MonoBehaviour {

public Button btnChangeImage;
public Text txtImageName;
public Image imgImage;

Sprite[] arrSprites;
int spriteIndexInArray = -1;

// Use this for initialization
void Start () {

Debug.Log("Try to load : sprite-atlas ");
arrSprites = Resources.LoadAll<Sprite>("sprite-atlas");
Debug.Log(arrSprites.Length);


foreach (Sprite lvSprite in arrSprites)
{
Debug.Log(lvSprite.name);

}

ChangeImage();

}

// Update is called once per frame
void Update () {

}

// Call this function when button click
public void ChangeImage(){

spriteIndexInArray = spriteIndexInArray < arrSprites.Length - 1 ? spriteIndexInArray + 1 : 0;


Debug.Log ("spriteIndexInArray : " + spriteIndexInArray );

imgImage.sprite = arrSprites[spriteIndexInArray];
txtImageName.text = arrSprites[spriteIndexInArray].name;
}
}




9. Drag-n-drop UI elements to "SpriteAtlasController.cs" script

Unity3D load sprite atlas from Resources - tutorial 11


10. Add OnClick call of method "ChangeImage()" for Button in UI

Unity3D load sprite atlas from Resources - tutorial 12


Hooray!!! :)

No comments:

Post a Comment