- Home /
How to divide Sprite texture dynamically?
Dear all friends using Unity,
My name is Sokmeng, a junior unity programmer, and currently I have a problem with Sprite Texture.
Normally I can use sprite editor to divide one texture to several pieces and drag all of those generated pieces to the Hierarchy. However, I just want to do it dynamically with c# script to divide sprite texture and assign those generated piece onto the hierarchy.
The reason for this question is that I want to create a dynamic Puzzle Game on Unity.
I look forward to hearing from you. Thanks!
Answer by JustFun · Sep 09, 2014 at 01:05 PM
Here's a simple example. Texture of size 1024x1024 is being cut into 64 equal pieces(8x8) and then they are placed on equal distance. All sprites are parented by some gameobject called "SpritesRoot", which exists in the scene.
using UnityEngine;
using System.Collections;
public class TextureDivider : MonoBehaviour {
public Texture2D source;
// Use this for initialization
void Start () {
GameObject spritesRoot = GameObject.Find("SpritesRoot");
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
Sprite newSprite = Sprite.Create(source, new Rect(i*128, j*128, 128, 128), new Vector2(0.5f, 0.5f));
GameObject n = new GameObject();
SpriteRenderer sr = n.AddComponent<SpriteRenderer>();
sr.sprite = newSprite;
n.transform.position = new Vector3(i*2, j*2 , 0);
n.transform.parent = spritesRoot.transform;
}
}
}
}
In Sprite.Create function 128 is the size of tile. Vector2(0.5f, 0.5f) makes sprites pivot to be placed in the center of tile.
Good answer - but how would you split up a texture into non-rectangular parts? Procedurally splitting a square or other into a triangles for example.
I guess you have to edit sprite or texture then, and set part or your image as fully transparent.
I have 9 objects. how can we place the pieces without add? I couldn't do it
Texture2D img = QuestionImage[Random.Range(0, QuestionImage.Length)];
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
Sprite newSprite = Sprite.Create(img, new Rect(i * 200, j * 200, 200, 200), new Vector2(0.5f, 0.5f));
Image image = list.GetComponentInChildren<Image>();
image.sprite = newSprite;
}
}
Answer by ismaelnascimento01 · Sep 13, 2017 at 07:42 PM
This approach works for me, but it is a bit slow. I am starting from a 2000x2000 image and slicing into 25 frames and this takes around 1 second. I would be interested in ideas for how to speed this up.
Your answer

Follow this Question
Related Questions
How to do make up using brush to draw sprite and remove using shower? 2 Answers
Screen resolution make sprites pixelated 0 Answers
How to make a different sprite load after every hit? 1 Answer
GameObject With Background Covers GameObject Without Background 1 Answer
How to merge Sorting Layers ? 1 Answer