Last active
August 29, 2015 14:20
-
-
Save matiasbeckerle/3126b118c3acfae4dddf to your computer and use it in GitHub Desktop.
Script for Unity5 to achieve a shield effect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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