Created
July 23, 2014 15:55
-
-
Save ashblue/9826ae3a0c59658db44a to your computer and use it in GitHub Desktop.
Unity 2d repeating sprite
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ?