In the Zombie Runner project, we are introduced to messages. This seemed a logical approach to making the project simpler. I set up a hierarchy as follows, with the intent to pass messages between objects to loosely couple the system. As there are few objects, a Broadcast Message doesn't seem too resource intensive.
mainTexture = new Texture2D(1, 1);
mainTexture.SetPixel(0, 0, mainColor);
mainTexture.wrapMode = TextureWrapMode.Repeat;
Given the texture, one simply needs to attach it to the SpriteRenderer. This was done as follows:
Rect unit = new Rect(0, 0, 1, 1);
SpriteRenderer sr = gameObject.GetComponent<SpriteRenderer>();
sr.sprite = Sprite.Create(backgroundTexture, unit, Vector3.zero);
Beyond that, I drew the background first. Then I drew the foreground as a child of the background. Finally, I updated the scale based on the health, making sure to clamp between 0 and 1.
To inform the object that it was dead, I used SendMessageUpwards("Die");. The object informed the Health that it was hit by using BroadcastMessage("SubtractHealth",10); And that was it. I did some testing, tweaking, and produced my final version, which I intend to use for other purposes.
Ben Pearson is the author of the Amateur Radio and other technology blog KD7UIY and developer of Games and Apps at Google Play pearsonartphoto, where he plans to publish some of the games created by inspiration of gamedev.tv. He is currently working on a Sea Trading game, which you can subscribe to updates at his Google Group. He has been a programmer since a young age, although only recently is learning programming with game engines. He has completed the the Complete Unity Developer Course and the Procedural Generation courses, and is working through the Complete Blender Developer Course and Unity Game Physics courses. He is hoping to soon start Unreal Courses soon. Follow him on Twitter @KD7UIY.