Skip to content

Instantly share code, notes, and snippets.

@wallstop
Created July 9, 2018 05:24
Show Gist options
  • Save wallstop/302522b2c6571f0e92fbf0c6c4c4d50a to your computer and use it in GitHub Desktop.
Save wallstop/302522b2c6571f0e92fbf0c6c4c4d50a to your computer and use it in GitHub Desktop.
using System;
using JetBrains.Annotations;
using UnityEngine;
namespace Assets.Scripts.Utility
{
[RequireComponent(typeof(SpriteRenderer))]
[RequireComponent(typeof(RectTransform))]
public sealed class SimpleSpriteColor : MonoBehaviour
{
public Color Color = Color.white;
private SpriteRenderer _renderer;
private RectTransform _transform;
[UsedImplicitly]
private void Start()
{
_transform = GetComponent<RectTransform>();
_renderer = GetComponent<SpriteRenderer>();
_renderer.sprite = Sprite.Create(WhiteTexture, new Rect(0, 0, Width, Height), new Vector2(0.5f, 0.5f), 1);
_renderer.color = Color;
}
private float Width => _transform.rect.width;
private float Height => _transform.rect.height;
private Texture2D WhiteTexture
{
get
{
float width = Width;
float height = Height;
Texture2D whiteTexture = Texture2D.whiteTexture;
whiteTexture.Resize((int)Math.Ceiling(width), (int)Math.Ceiling(height));
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
whiteTexture.SetPixel(x, y, Color.white);
}
}
whiteTexture.wrapMode = TextureWrapMode.Repeat;
whiteTexture.Apply();
return whiteTexture;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment