Tutorial: 1st-person sneak in Unity 5, part 6

Previous parts of tutorial

Next I setup something for regaining energy and health. I want the PC to be gain health or power while it stands next to the power-up (and as long as the power-up have something to left to give). The power-up keep its state so that it does not pop us as full if the PC gets back to the level. I also want to visualise in some degree how much health/energy power-up has left or if it is fully drained.


using UnityEngine;
using System.Collections;

public class PowerUp : MonoBehaviour {
	public enum PUType {HEALTH,ENERGY};
        // menu to choose if this gives health or energy
	public PUType type;
        // how much energy there is left in power-uo
	public int amount = 0;
        // and the full amount
	public int full = 50;
        // how fast the health/energy get transferred
	public int transferAmountInTick = 1;
	public float transferInerval = 0.1f;
        // link to the render of the object so that we can manipulate
        // material
	public Renderer meshRenderer;
        // effect to illustrate that something is transferring from power-up
        // to player. Particle effect prefab should go here
	public GameObject transferEffect; 
	private GameObject effect;
	private string amount_key;
	private AudioSource audioSource;
	private Color emisCol;
	void Awake() {
		audioSource = GetComponent();
	void Start() {
                // checking if we need to read save data or reset power-up as full
		amount_key = System.String.Format("{0}_a", name);
		string sqn_key = System.String.Format("{0}_sqn", name);
		Debug.Log ("PowerUp.Start() GameSqn = " + GameAgents.GameSqn() + ", " +  name + " sqn = " + PlayerPrefs.GetInt(sqn_key));
		if(GameAgents.GameSqn() > PlayerPrefs.GetInt(sqn_key)) {
			amount = full;
			Debug.Log ("PowerUp.Start(): Reseting powerup amount = " + amount);
			PlayerPrefs.SetInt(sqn_key, GameAgents.GameSqn());
		else {
			amount = PlayerPrefs.GetInt(amount_key, full);
			Debug.Log ("PowerUp.Start(): reading save amount = " + amount);
                // to illustrate how full the power-up is, I manipulate emission color
		emisCol = meshRenderer.material.GetColor ("_EmissionColor");
	void OnTriggerEnter(Collider other) {
		// some object collided to power-up
		if(other.gameObject == GameAgents.GetPlayer()) {
                        // object is the PC
			if( ChargeLeft() ) {
                                // power-up is not empty

                                // check if the PC needs to health/energy
                                // if not return
				if( (type == PUType.HEALTH &&  GameAgents.GetCharacterInterface().CanUseHealth() == false) ||
				    (type == PUType.ENERGY && GameAgents.GetCharacterInterface().CanUseEnergy() == false)) {
                                // start audio and visual effects illustrating
                                // that the PC is gaining health/energy
				if( ! audioSource.isPlaying ) {
				if(transferEffect != null) {
					effect = Instantiate(transferEffect, (other.transform.position-transform.position)/2+transform.position+new Vector3(0,0.5f,0), Quaternion.identity) as GameObject;
				else {
					effect = null;
                                // start actual transfer if needed.
				if( ! IsInvoking() ) {
					InvokeRepeating("Transfer", 0, 0.1f);
	void OnTriggerExit() {
                // the PC moved way from 
		audioSource.Stop ();
		if(effect) {
			effect = null;
		GameAgents.GetCharacterInterface().Save ();
	private bool ChargeLeft() {
		if(amount - transferAmountInTick >= 0) {
			return true;
		else {
			return false;
	private void Transfer() {
		amount -= transferAmountInTick;
		PlayerPrefs.SetInt(amount_key, amount);
		switch(type) {
		case PUType.HEALTH:
			GameAgents.GetCharacterInterface().PowerUp(0, transferAmountInTick);
		case PUType.ENERGY:
			GameAgents.GetCharacterInterface().PowerUp(transferAmountInTick, 0);
		if(ChargeLeft() == false) {
			if(effect) {
				effect = null;
			GameAgents.GetCharacterInterface().Save ();
	private void SetEmisColor() {
		float e = (float)amount/(float)full;
		Color finalColor = emisCol * Mathf.LinearToGammaSpace (e);
		meshRenderer.material.SetColor ("_EmissionColor", finalColor);

I need to game objects: one for power and another for health recharging stations. The models in image are from asset store (Scifi Battery by 256px and Toughbook published by Unity; with cube added.)

Power recharging station object & PowerUp script setup
Power recharging station object & PowerUp script setup

PowerTransferEffect is an object containing particle effects. The particle effect object is instantiated when the PC is draining health or power and destroyed when draining stopped.

Material of the object needs to use Standard Shader. I added emission texture where I marked illuminated area with with white and non-illuminated with black (if you take Alberto image as reference it is easy to match emission to correct areas).

Published by lankoski

Petri Lankoski, D.Arts, is a Associate Professor in Game Studies at the school of Communication, Media and IT at the Södertörn University, Sweden. His research focuses on game design, game characters, role-playing, and playing experience. Petri has been concentrating on single-player video games but researched also (multi-player) pnp and live-action role-playing games. This blog focuses on his research on games and related things.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: