I’m trying to create a timer that expires every X seconds. Upon expiring, it casts a spell. It does this X number of times then deletes itself. But no matter what I do my timer always remains and is never destroyed. I also get the error “…can only be called from the MainThread.”
using UnityEngine;
using System.Collections;
using System.Timers;
public class AttackBehaviour : MonoBehaviour
{
public bool canAttack;
public double attackInterval;
public Spell[] spells = new Spell[1];
public int numberOfAttacks;
int attacks;
Vector2 targetPos;
Timer timer;
void Awake ()
{
timer = new Timer (attackInterval);
timer.Elapsed += OnTimerEnds;
timer.Enabled = true;
targetPos = new Vector2 (0, 0);
spells [0].Cast (targetPos);
}
void OnTimerEnds (object source, ElapsedEventArgs e)
{
if (attacks < numberOfAttacks) {
Debug.Log ("Frozen Orb Nova");
//int i = Random.Range (0, spells.Length - 1);
//spells [0].Cast (targetPos);
attacks++;
timer.Elapsed -= OnTimerEnds;
timer.Dispose ();
timer.Stop ();
timer.Enabled = false;
} else {
Debug.Log ("Over.");
timer.Dispose ();
Destroy (this);
}
}
}