I'm trying to create a Tiled Sprite, what am I doing wrong?

Since apparently Unity 2D still lacks tiled sprites, I’m tyring to create a class which takes a normal Sprite and tiles it using custom dimentions.

It doesn’t crash, but doesn’t yield results either: I just get an empty sprite apparently.

The transform position is correct (unaltered), I do use Apply, and the new width is multiple of the original one. Now I’m clueless about what could be the problem.

Hint: I’m >>>NOT<<< talking about atlases, which now are natively supported, I’m talking about having a single sprite and displaying tiled multiple times (which might be supported in future, but currently apparently isn’t)

Here’s the script, can anybody help?

using UnityEngine;
using System.Collections;

public class TiledSprite : MonoBehaviour
{
	public int width,height;

	private SpriteRenderer renderer;
	private Sprite originalSprite;

	void Awake ()
	{
		renderer=GetComponent<SpriteRenderer>();
		originalSprite=renderer.sprite;

		// crea il nuovo Sprite

		Texture2D target = new Texture2D(width,height);
		int ow = originalSprite.texture.width;
		int oh = originalSprite.texture.height;

		Color32[] pixOrig = originalSprite.texture.GetPixels32();
		Color32[] pixDest = new Color32[width*height];

		int osize=ow*oh,dsize=width*height;
		int cur=0;
		while (cur<dsize)
		{
			for (int cur2=0; cur2<osize; cur2++)
			{
				pixDest[cur++]=pixOrig[cur2];
			}
		}

		target.SetPixels32(pixDest);
		target.Apply();

		Sprite newSprite = Sprite.Create(target,new Rect(0,0,width,height),new Vector2(width/2,height/2));
		renderer.sprite=newSprite;
	}
}

While I still have no clue why this didn’t work, I’ve been helped into a much more direct solution: Unity already supports this kind of thing, it’s just matter of knowing how to do that.

  1. set your image Texture Type: Texture, Wrap Mode: Repeat
  2. create a new Material using that image, set the Shader: Particles/Alpha Blended, set the Tiling to how many times you want to repeat it
  3. in the scene create a Quad using that Material

Not a perfect solution, especially since you have to manually set the tiling in the Material itself, but was good enough for what I was doing.

This is quite easy to do with a simple script and nothing else except a sprite renderer. See my answer at the link below for more details (note it might not be live yet since I’m awaiting moderator approval).