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.
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.