0

I have 14 spikes which fall down when player go under them. So when player dies I need to come back spikes to initial position. I have 2 Vector3 arrays: in the first I copy spikes position at the beginning and in the second array there are current positions of spikes. So I tried to do it through for loop but it raises an error in the for loop in Start: IndexOutOfRangeException: Index was outside the bounds of the array. Could you say how can I do it right? Here is the code:

    private GameObject[] spikes;
    private Vector3[] spikes_pos;

    void Start()
    {
        spikes = GameObject.FindGameObjectsWithTag("spikes_3");
        spikes_pos = new Vector3[spikes.Length];
        for (int i = 0; i <= spikes.Length; i++)
        {
            spikes_pos[i] = spikes[i].transform.position;
        }

        private void OnCollisionEnter2D(Collision2D other)
        {
            if (other.gameObject == bottom || other.gameObject.CompareTag("Spike"))
            {
               for (int i = 0; i <= spikes.Length; i++)
               {
                spikes[i].transform.position = spikes_pos[i];
               }
        }
xogeh
  • 23
  • 5

1 Answers1

1

Keep in mind that arrays start with index 0 and end with the index that is one smaller than its length. You shouldn't use <= in your for loop condition i <= spikes.Length, just <.

Say you have an array of length 2 [8,9]. If you set the condition index <= array.Length or index <= 2 the for loop will return the following:

  • index 0 is less or equal 2, therefore we return the value at index 0, which is 8
  • index 1 is less or equal 2, therefore we return the value at index 1, which is 9
  • index 2 is less or equal 2, therefore we return the value at index 2, which does not exist/is out of bounds -> throw error
Voidsay
  • 1,462
  • 2
  • 3
  • 15