Skip to content

Instantly share code, notes, and snippets.

@ashblue
Created July 23, 2014 15:55
Show Gist options
  • Save ashblue/9826ae3a0c59658db44a to your computer and use it in GitHub Desktop.
Save ashblue/9826ae3a0c59658db44a to your computer and use it in GitHub Desktop.
Unity 2d repeating sprite
using UnityEngine;
using System.Collections;
// @NOTE the attached sprite's position should be "top left" or the children will not align properly
// Strech out the image as you need in the sprite render, the following script will auto-correct it
[RequireComponent (typeof (SpriteRenderer))]
// Generates a nice set of repeated sprites inside a streched sprite renderer
// @NOTE Vertical only, you can easily expand this to horizontal with a little tweaking
public class RepeatSpriteBoundary : MonoBehaviour {
SpriteRenderer sprite;
void Awake () {
// Get the current sprite with an unscaled size
sprite = GetComponent<SpriteRenderer>();
Vector2 spriteSize = new Vector2(sprite.bounds.size.x / transform.localScale.x, sprite.bounds.size.y / transform.localScale.y);
// Generate a child prefab of the sprite renderer
GameObject childPrefab = new GameObject();
SpriteRenderer childSprite = childPrefab.AddComponent<SpriteRenderer>();
childPrefab.transform.position = transform.position;
childSprite.sprite = sprite.sprite;
// Loop through and spit out repeated tiles
GameObject child;
for (int i = 1, l = (int)Mathf.Round(sprite.bounds.size.y); i < l; i++) {
child = Instantiate(childPrefab) as GameObject;
child.transform.position = transform.position - (new Vector3(0, spriteSize.y, 0) * i);
child.transform.parent = transform;
}
// Set the parent last on the prefab to prevent transform displacement
childPrefab.transform.parent = transform;
// Disable the currently existing sprite component since its now a repeated image
sprite.enabled = false;
}
}
@torta24
Copy link

torta24 commented May 25, 2015

I have a question .
If you are using "MonoBehaviour" then you shouldn't be using "new" keyword. Using new does not give an error so it is alright using "new" keyword ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment