0

I'm trying to use a loop to place my player in the seat that is empty which works fine but I'm trying to set a bool to false when the player leaves it but I can't seem to get access to it

IndexOutOfRangeException: Array index is out of range. GetIn.ExitObject () (at Assets/GetIn.cs:118) GetIn.Update () (at Assets/GetIn.cs:55)

    public int whatSeat;
    Transform TheObject;

    positions = TheObject.GetComponent<GetInObject>().PosInObect;
    for (whatSeat = 0; whatSeat < positions.Length; whatSeat++)
    {
        if (positions[whatSeat].isOccupied == false)
        {
            transform.parent = positions[whatSeat].pos;
            positions[whatSeat].isOccupied = true;
        }
    }

and then in another function I want to access the same whatSeat variable to turn it to false when you exit

positions[whatSeat].isOccupied = false;

but that is where the error crops up I don't know how to solve this

Delimitry
  • 2,987
  • 4
  • 30
  • 39
pvtctrlalt
  • 61
  • 2
  • 9
  • What is the value of `whatSeat` when you debug your code? Are you sure your `positions` have this index? Related: [What is an “index out of range” exception, and how do I fix it?](http://stackoverflow.com/questions/24812679/what-is-an-index-out-of-range-exception-and-how-do-i-fix-it) – Soner Gönül Apr 03 '15 at 08:27
  • 1
    Have you tried adding a "break;" after the "positions[whatSeat].isOccupied = true;" line? Then the loop will find the first unoccupied seat and finish. Leaving whatSeat as the newly occupied seat. – Taran Apr 03 '15 at 08:29
  • ok after putting in some debugs the whatseat changes to 1 so how do i go about adding this break in? – pvtctrlalt Apr 03 '15 at 08:32
  • Also make sure you don't use the same `whatSeat` variable to loop trough seats for multiple players or units (I assume there are more units since there are more seats). – B0Andrew Apr 03 '15 at 08:32
  • ok that break fixed it thanks do you wanna put that as an answer so i can accept it? – pvtctrlalt Apr 03 '15 at 08:33

1 Answers1

0

Try this:

    public int whatSeat;
    Transform TheObject;

    positions = TheObject.GetComponent<GetInObject>().PosInObect;
    for (whatSeat = 0; whatSeat < positions.Length; whatSeat++)
    {
        if (positions[whatSeat].isOccupied == false)
        {
            transform.parent = positions[whatSeat].pos;
            positions[whatSeat].isOccupied = true;
            break;   // Adding break here
        }
    }

Once you exit the loop, whatSeat will hold the value of the newly occupied seat.

Taran
  • 12,822
  • 3
  • 43
  • 47
  • ok i cant see the accept button atm as im using a networked computer that using internet explorer from like 2006 so when i get home ill accept it – pvtctrlalt Apr 03 '15 at 08:41