Skip to main content

Posts

Showing posts from December, 2015

Unity: How Adapters can help you write fewer MonoBehaviours

TL;DR: You don't need to duplicate a bunch of code to do the same things to a Image and a SpriteRenderer, or RectTransform and Transform, etc. You can use a simple pattern called the Adapter Pattern. If you've never used it before, this post explains how.

The Problem: Image vs SpriteRenderer Lets say you want to make a sprite fade out, maybe its a dead monster or a collectible, but in either case you want it to gracefully depart from the screen rather than blink out of existence. Kinda like this eyeball monster from Beastly:


So that's pretty easy right, one way of doing it is with a MonoBehaviour that modifies the sprites alpha value via SpriteRenderer.color. Your class might look something like this:
public class AlphaFaderSprite : MonoBehaviour { public SpriteRenderer spr; public float fade_percentage; void Update() { spr.color = new Color(spr.color.r, spr.color.g, spr.color.b, fade_percentage); } } Now, anyone who's used Unity for more than an …