Hey Developers!
The code I will post below is working perfectly fine, but I was just wondering if there was an alternative way of achieving this? To make it easier to understand, this is what the code is doing:
- Check if Fan Status is Set To False
- Start Fan Start Countdown
- Switch Fan On (Change Sprite Color)
- Switch Fan Off (Change Sprite Color x2)
- Repeat…
Thank you all for viewing or contributing!
using UnityEngine;
using System.Collections;
public class PlatformFan : MonoBehaviour
{
// Variable Determine If Fan is On/Off
public bool FanActivated = false; // Set to False By Default
// Variable Determine The Fan On Duration
public float FanOnTimer = 2.0f;
public float FanCountdownTimer;
// Variable Stores The Fan Sprite Renderer
private SpriteRenderer FanSpriteRenderer;
// Variable Stores The Fan On/Off State
public Color RedColor; // Switched On
public Color AmberColor; // About To Go Off
public Color GreenColor; // Switched Off
// Use this for initialization
void Start ()
{
// Get Sprite Renderer Component
FanSpriteRenderer = gameObject.GetComponent<SpriteRenderer>();
// Create a Copy Of Fan On Timer
FanCountdownTimer = FanOnTimer;
}
// Update is called once per frame
void Update ()
{
// Check If Fan is Activated
if(FanActivated == false)
{
if(FanCountdownTimer >= 0)
{
Debug.Log("Fan Countdown Started!");
// Start Countdown
FanCountdownTimer -= Time.deltaTime;
}
else
{
// Execute Method To Switch Fan On
SwitchFanOn();
}
}
}
// Method To Switch Fan On
void SwitchFanOn()
{
Debug.Log("Fan Switched On!");
// Set Fan Status To True
FanActivated = true;
// Set Fan Color To Green
FanSpriteRenderer.color = GreenColor;
// Execute Method to Switch Fan Off
StartCoroutine(SwitchFanOff());
}
// Method To Switch Fan Off
IEnumerator SwitchFanOff()
{
// Divide Fan Timer So We Could Change The Color Twice
float CurrentFanTimer = FanOnTimer/2;
// Wait Amount Of Time Before Proceed Ahead
yield return new WaitForSeconds(CurrentFanTimer);
// Set Fan Color To Amber
FanSpriteRenderer.color = AmberColor;
// Wait Amount Of Time Before Proceed Ahead
yield return new WaitForSeconds(CurrentFanTimer);
// Set Fan Color To Red
FanSpriteRenderer.color = RedColor;
// Set Fan Status To False
FanActivated = false;
// Reset Countdown Timer
FanCountdownTimer = FanOnTimer;
Debug.Log("Fan Switched Off!");
}
}