Skip to content

Instantly share code, notes, and snippets.

@matiasbeckerle
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matiasbeckerle/3126b118c3acfae4dddf to your computer and use it in GitHub Desktop.
Save matiasbeckerle/3126b118c3acfae4dddf to your computer and use it in GitHub Desktop.
Script for Unity5 to achieve a shield effect
using UnityEngine;
using System.Collections;
public class Shield : MonoBehaviour
{
/// <summary>
/// This is the maximum alpha value possible by this shield.
/// From 0 to 255. When close to 255, more solid will be.
/// </summary>
public int MaxAlpha = 10;
private Renderer myRenderer;
void Start()
{
myRenderer = GetComponent<Renderer>();
}
/// <summary>
/// Fades the shield after collision.
/// To know more about Standard Shader properties, check out the material with the inspector in debug mode.
/// </summary>
/// <returns>Nothing.</returns>
IEnumerator Fade()
{
Color color = myRenderer.sharedMaterial.color;
for (float alpha = 1f; alpha >= 0; alpha -= 0.1f)
{
// Decrease alpha material color little by little
color.a = (alpha * MaxAlpha) / 255;
// Set shader properties
myRenderer.sharedMaterial.SetVector("_Color", color);
myRenderer.sharedMaterial.SetFloat("_Glossiness", alpha);
yield return null;
}
}
/// <summary>
/// Shows up the shield in a collision.
/// To know more about Standard Shader properties, check out the material with the inspector in debug mode.
/// </summary>
void Show()
{
// Give some alpha to material color
Color color = myRenderer.sharedMaterial.color;
color.a = MaxAlpha / 255;
// Set shader properties
myRenderer.sharedMaterial.SetVector("_Color", color);
myRenderer.sharedMaterial.SetFloat("_Glossiness", 1);
StartCoroutine(Fade());
}
void OnCollisionEnter(Collision collision)
{
foreach (var contact in collision.contacts)
{
Show();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment