sokorota
sokorota

Reputation: 19

How to output all members of my list correctly?

I want the members of my list "questPartyMembers" to all output with the Debug.LogFormat method. I'm not sure how to proceed. I tried it once with only one member and that member was spent, but I don't know how to go on. I always get an exception:

ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index System.ThrowHelper.ThrowArgumentOutOfRangeException (System.ExceptionArgument argument, System.ExceptionResource resource) (at <1f0c1ef1ad524c38bbc5536809c46b48>:0) System.ThrowHelper.ThrowArgumentOutOfRangeException () (at <1f0c1ef1ad524c38bbc5536809c46b48>:0) System.Collections.Generic.List`1[T].get_Item (System.Int32 index) (at <1f0c1ef1ad524c38bbc5536809c46b48>:0) TheChoosen.Update () (at Assets/TheChoosen.cs:124)

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

public class TheChoosen : MonoBehaviour
{
    public string weaponType;
    public bool haveWeapon = false;
    public string characterType = "Farmer";
    public string firstName;
    public bool allGood;
    public int gold;
    public bool hasDungeonKey = false;
    public int progress = 0;
    public List<String> questPartyMembers;


    void Start()
    {
        questPartyMembers = new List<String>() { "Grim the Barbarian", "Merlin the Wise", "Sterling the Knight" };
        firstName = "Robert";
        gold = 10;
        weaponType = "dagger of Sabbatooth";
        GenerateCharacter();
    }


    public void GenerateCharacter()
    {
        Debug.Log("Hello " + firstName);
        Debug.Log("Ready to go on an adventure?");
        Debug.Log("Type y to answer with yes!");



    }

    public void startAdventure()
    {
        Debug.Log("Let's go");
        progress++;
    }

    public void theAdventure()
    {
        Debug.Log("Your current Gold:" + gold);
        Debug.Log("Look around? (s)");
        progress++;
     }

    public void look01()
    {

        if (Input.GetKeyDown(KeyCode.S))
        {
            Debug.Log("You're in front of a big oak tree. " +
                "There is a large chest on the floor. " +
                "Looks like it can be opened easily.");
            Debug.Log("Open Chest? (o)");
            progress++;
        }
    }
    public void OpenFstChest()
    {
        if (Input.GetKeyDown(KeyCode.O))
        {
            Debug.Log("The box opens loudly creaking and reveals the " +
                "view of a large, strangely shining dagger.");
            Debug.Log("Take the weapon with 't'.");
            progress++;
        }
    }

    public void GetWeaponOne()
    {

        if (Input.GetKeyDown(KeyCode.T))
        {
            haveWeapon = true;
            Debug.Log("You now have the " + weaponType);
            Debug.Log("Show QuestPartyMembers? (Q)");

            progress++;
        }
    }


    void Update()
    {
        switch (progress)
        {
            case 0:
                if (Input.GetKeyDown(KeyCode.Y))
                {
                    startAdventure();
                }
                break;
            case 1:
                theAdventure();
                break;
            case 2:

                    look01();
                 break;

            case 3:
                OpenFstChest();
                    break;

            case 4:
                GetWeaponOne();
                break;

            case 5:
                if (Input.GetKeyDown(KeyCode.Q))
                {
                    Debug.LogFormat("Members: {0}", questPartyMembers[0], questPartyMembers[1], questPartyMembers[2], questPartyMembers[3]);
                }
                break;
        }
      }
    }

Upvotes: 0

Views: 256

Answers (2)

Chrᴉz remembers Monica
Chrᴉz remembers Monica

Reputation: 1904

Your List questPartyMembers only has 3 entries:

void Start()
{
    questPartyMembers = new List<String>() { "Grim the Barbarian", "Merlin the Wise", "Sterling the Knight" };
    ...
}

But you want to output 4 members later on:

case 5:
    if (Input.GetKeyDown(KeyCode.Q))
    {
        Debug.LogFormat("Members: {0}", questPartyMembers[0], questPartyMembers[1], questPartyMembers[2], questPartyMembers[3]);
    }
    break;

With questPartyMembers[3] you access your 4th (0-based) element in the list which causes the error. Also, your Elements in your format string dont fit with the ones in your parameters. Use Debug.LogFormat("Members: {0}", String.Join(", ", questPartyMembers[0], questPartyMembers[1], questPartyMembers[2])); or Debug.LogFormat("Members: {0}, {1} and {2}", questPartyMembers[0], questPartyMembers[1], questPartyMembers[2]); instead.

Upvotes: 0

WQYeo
WQYeo

Reputation: 4071

In your switch statement, you had this:

Debug.LogFormat("Members: {0}", questPartyMembers[0], questPartyMembers[1], questPartyMembers[2], questPartyMembers[3])

This code strongly relies on the fact that there must be at least 4 members in your team (questPartyMembers).
If there is anything less, an exception will be thrown (aka you might be trying to access the 4th member in the party even though there is only three).

You can try using a foreach loop if you want to print out all of them, like so:

foreach (var member in questPartyMembers){
  Debug.Log(member); // Or print something else related to the member
}

Small Edit

Alternatively, if you want to print out all of the member's in 1 line, loop through all of them, and add them to a string, like so:

StringBuilder members = new StringBuilder();
for (int i = 0; i < questPartyMembers.Count; ++i){
  members.Append(questPartyMembers[i]);

  // Adds a comma if this is not the last member.
  if (i != questPartyMembers.Count - 1){
    members.Append(", ");
  }
}
Debug.Log(members.ToString());

Upvotes: 1

Related Questions