ArgumentOutOfRangeException is occuring when it shouldn't
I've been working on a project for a while now, and only recently has my code started to bug out a bit where it is telling me that I have an ArgumentOutOfRangeException
on a list of UnityEvents
, I have no idea why this is, it worked just fine earlier today. I've been at this problem now for some 3~4 hours with no answer in sight.
The int Player.mouseID
is not the issue as i have been monitoring it's value and it's never negative, and availableEvents is being set in the editor.
using UnityEngine;
using UnityEngine.Events;
using PointAndClickEngine;
public class MouseInteractionScript : MonoBehaviour
{
public UnityEvent[] availableEvents = new UnityEvent[12];
void Awake ()
{
Collider2D col2D = gameObject.AddComponent<BoxCollider2D>() as BoxCollider2D;
}
void OnMouseDown ()
{
//Debug.Log(availableEvents.Count);
if( (Player.mouseID <= availableEvents.Length - 1) && (Player.mouseID >= 0) )
{
if (availableEvents[Player.mouseID].GetPersistentEventCount() != 0)
{
Debug.Log(Player.mouseID);
availableEvents[Player.mouseID].Invoke(); //This is the line giving the error
}
else
{
DesignUtility.DisplayNoResult();
Debug.Log(this.gameObject);
}
}
else
{
DesignUtility.DisplayNoResult();
Debug.Log(this.gameObject);
}
}
}
You need to share an actual and full call stack, otherwise ppl can offer merely conjectures.
Judging by the code you seem to overestimate that Player.mouseID
is out of range while neglecting the chance that code run by .Invoke();
is to blame instead.
Also, consider storing copies of properties etc. as local variables. It sometimes can reduce cpu work while making your code tiny bit more predictable.
void OnMouseDown ()
{
int mouseID = Player.mouseID;
if( mouseID<availableEvents.Length && mouseID>=0 )
{
var mouseEvent = availableEvents[mouseID];
if( mouseEvent.GetPersistentEventCount()!=0 )
mouseEvent.Invoke();
else
DesignUtility.DisplayNoResult();
}
else
DesignUtility.DisplayNoResult();
}