0
\$\begingroup\$

I have two GameObjects in an array, and the S key is used to cycle an index referring the objects in this array.

When I run the game for the first time and press S, it changes from 0 to 1 and then to 2. After that it just cycles between 1 and 2... but it should be changing between 0 and 1 only; there are only two objects.

Why is this behavior occurring? My code is below:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SwitchObjects : MonoBehaviour
{
    public GameObject[] objects;
    public int activeIndex = 0;

    public void SetActiveObject(int aIndex)
    {
        activeIndex = aIndex;
        for (int i = 0; i < objects.Length; i++)
            objects[i].SetActive(i == activeIndex);
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.S))
        {
            if (activeIndex == objects.Length)
                activeIndex = 0;
            activeIndex++;
            SetActiveObject(activeIndex);
        }
    }
}
\$\endgroup\$
3
\$\begingroup\$

I belive your problem is here:

        if (activeIndex == objects.Length)
            activeIndex = 0;
        activeIndex++;

You set activeIndex to zero, but then increment it immediately. So the solution should be:

if (activeIndex == objects.Length)
    activeIndex = 0;
else
    activeIndex++;
\$\endgroup\$
  • \$\begingroup\$ your solution is working but I also needed to change this line: if (activeIndex == objects.Length - 1) Only if I'm adding -1 it's changing between the two indexs 0 and 1. Without it, it will keep changing between indexs 0 1 and 2 and I can't figure out what is index 2 if there are only two objects in the array. So adding -1 make it acting like I wanted. \$\endgroup\$ – jdoedoe doedoe Feb 2 '18 at 16:36
  • 1
    \$\begingroup\$ You get index 2 because it is the number of elements inside objects. And yes, you're right, completely forgot about -1. \$\endgroup\$ – Vadimz Feb 2 '18 at 16:49
3
\$\begingroup\$
if (activeIndex == objects.Length)
                activeIndex = 0;
++activeIndex;

This statement resets activeIndex to 0 then immediately adds 1, so activeIndex can never be reset to 0.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.