FANDOM


The following script can be used to automatically reduce a Global Integer variable's value by 1 every second, and run an ActionList asset when it hits zero.

Doing so in this script is more efficient than running an ActionList, as multiple timers can be created in the same component.

To use it, paste the following code into a C# script named VariableTimers.cs, and add the Variable Timer component to your scene. Configure its Inspector to create new timers by assigning the ID number of the variable you wish to countdown.

VariableTimers.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using AC;

public class VariableTimers : MonoBehaviour
{

public VariableTimer[] timers;
private float ticker = 1f;
private int numTimers;
private int i;


private void Awake ()
{
numTimers = timers.Length;
}


private void Update ()
{
ticker -= Time.deltaTime;
if (ticker <= 0f)
{
ticker = 1f;

for (i=0; i<numTimers; i++)
{
timers[i].Update ();
}
}
}


[System.Serializable]
public class VariableTimer
{

public int globalIntegerVariableID;
public bool doCountdown = true;
public ActionListAsset actionListOnHitZero = null;


public void Update ()
{
if (doCountdown && Variable != null && Variable.IntegerValue > 0)
{
Variable.IntegerValue --;
if (Variable.IntegerValue == 0 && actionListOnHitZero != null)
{
actionListOnHitZero.Interact ();
}
}
}


private GVar variable;
private GVar Variable
{
get
{
if (variable == null)
{
variable = GlobalVariables.GetVariable (globalIntegerVariableID);
}
if (variable == null)
{
Debug.LogWarning ("AC Global Variable with ID=" + globalIntegerVariableID + " not found!");
}
return variable;
}
}

}

}
Community content is available under CC-BY-SA unless otherwise noted.