Trabla: Unity3D: loading and using sprite atlas from Resources
Solving:
1. Create sprite atlas ( .png file images, background transparent )
"sprite-atlas.png" File
2. Create new unity2D project
3. Create folder "Resources" in folder "Assets"
and drag-n-drop sprite atlas file into folder "Resources"
4. Select sprite atlas file - set "Sprite Mode" -> "Multiple" + click "Apply"
5. Click "Sprite Editor" - slice sprite in automatic mode - will create separate sprites.
Slice Result
6. Create following UI structure:
Panel
- Text
- Button
- Image
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
10. Add OnClick call of method "ChangeImage()" for Button in UI
Hooray!!! :)
No comments:
Post a Comment