Search Unity

Question ArgumentOutOfRangeException error but the script still works

Discussion in 'Scripting' started by MqcCheeze, Oct 23, 2022.

  1. MqcCheeze

    MqcCheeze

    Joined:
    Jun 21, 2021
    Posts:
    16
    The script is the exact same 5 minutes before this error started appearing, I don't know what happened to it, but now this error keeps coming up, and if I try to play in the editor, everything seems to work fine. I don't have a clue what this is talking about
    upload_2022-10-23_13-1-30.png
    This is the error


    upload_2022-10-23_13-1-48.png
    This is the code that I'm trying to run
    upload_2022-10-23_13-4-50.png
    This is how I created the script that holds the GameObjects

    upload_2022-10-23_13-2-9.png
    And as you can see, every element in the list has a GameObject assigned to it.

    VS studio says that the min and max values of a Random.Range() is inclusive so I shouldn't need to put patrolPoints.Count -1 as the maximum, and even if I do, the error still comes up.

    I don't know what is wrong with my code, whether its something I'm overlooking or whatever, I'm just confused why the error started appearing even though I didn't change the script.
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    5,990
    The problem is definitely with that Random.Range() index. Try logging it:
    Code (CSharp):
    1. var index = Random.Range(0, patrolPoints.Count);
    2. Debug.Log($"using index {index} from list with {patrolPoints.Count} items");
    3. var patrolPoint = patrolPoints[index].GetComponent<Transform>();
    I can imagine the size of the list changing, or it being replaced with another list, or you have another Enemy where the list isn't initialized and for some reason that causes the exception only after some time.