Hi,
I am trying to learn some C#, and to that end I made this script to practice implementing a few things (properties, events, general C# syntax).
The script:
using UnityEngine;
using System.Collections;
public class Timer : MonoBehaviour
{
private static float timeLeft;
private static bool isTiming = false;
public static float TimeLeft
{
get { return timeLeft; }
set { timeLeft = value; }
}
public delegate void CountdownEndedHandler ();
public static event CountdownEndedHandler CountdownEnded;
public static void CountDownFrom (float countdownTime)
{
if (isTiming) return;
else
{
Debug.Log("CountDownFrom " + countdownTime);
isTiming = true;
timeLeft = countdownTime;
StartCoroutine(Countdown(countdownTime));
}
}
private static IEnumerator Countdown (float countdownTime)
{
Debug.Log("Firing Countdown()");
if (timeLeft <= 0) EndCountdown();
else
{
yield return new WaitForFixedUpdate();
timeLeft -= Time.deltaTime;
Debug.Log("timeleft = " + timeLeft);
}
}
private static void EndCountdown ()
{
StopAllCoroutines();
isTiming = false;
timeLeft = 0f;
if (CountdownEnded != null) CountdownEnded();
}
}
However, I am getting the following errors:
Assets/Scripts/Timer.cs(28,25): error CS0120: An object reference is required to access non-static member `UnityEngine.MonoBehaviour.StartCoroutine(System.Collections.IEnumerator)'
Assets/Scripts/Timer.cs(46,17): error CS0120: An object reference is required to access non-static member `UnityEngine.MonoBehaviour.StopAllCoroutines()'
Part of my objective in this exercise is to create a class that has methods that can be called from other scripts, without this particular class having any instance of itself (i.e., the script lives only in my ‘Scripts’ folder, and is not attached to any GO), which is why everything is set to ‘static’. (That’s my understanding of what ‘static’ does – makes things available on a more global level as opposed to from an individual instance of something.)
Can anyone help me understand what I’m doing wrong / missing here?
Thanks!