JoeFish
JoeFish

Reputation: 19

"for" loop with IEnumerator coroutine containing a yied return not looping

I am selecting data from a database and then assigning that data to values in an array in my unity project using c#. The database is accessed with php scripts and my game calls the scripts on the server. My plan is to increment the ship number and use the same script calling on a different ship in the database. This is all working well except my loop in c#, which executes only once. Here is my code. shipsAllowed is set at 2 right now for testing purposes and there is record for this ship in the database. So what am I doing wrong, seems straight forward but is not working for me. Thanks for any help.

public void AddShipsToShipsArray()
{
    for (int x = 1; x < ShipsAllowed; x++)
    {
        StartCoroutine(GetShipInfoFromDB(x));
    }
}

IEnumerator GetShipInfoFromDB(int x)
{

    shipInfoUrl = "http://localhost/fishwar/GetShipInfo.php?shipnum=" + x + "&id=" + accountNumber;
    WWW shipInfoWWW = new WWW(shipInfoUrl);
    yield return shipInfoWWW;
    shipinfoRawString = shipInfoWWW.text;

    Dictionary<string, object> shipInfo = MiniJSON.Json.Deserialize(shipinfoRawString) as Dictionary<string, object>;

    shipArrayPosition = int.Parse((string)shipInfo["array_position"]);
    ships[shipArrayPosition].shipName = (string)shipInfo["ship_name"];
    ships[shipArrayPosition].departureTime = DateTime.Parse((string)shipInfo["departure_time"]);
    ships[shipArrayPosition].isAtSea = bool.Parse((string)shipInfo["is_at_sea"]);
}

Upvotes: 0

Views: 473

Answers (1)

Mage Xy
Mage Xy

Reputation: 1803

Change the exit condition in your loop to use less-than-or-equal-to:

for (int x = 1; x <= ShipsAllowed; x++) // Change made on this line.
{
    StartCoroutine(GetShipInfoFromDB(x));
}

Upvotes: 4

Related Questions