TransWikia.com

Can't use saved information to load into an array

Stack Overflow Asked by Danny on August 13, 2020

I’ve managed to save some information into a file. I want to be able to read that information and use it to create an item

public void Save()
{            
   StreamWriter writer;
   writer = new StreamWriter("PlayerInventory.txt");
   for (int i = 0; i < playerInventory.Length; i++)
   {
      if (playerInventory[i] != null)
      {
         if (playerInventory[i] is Sheild sheild)
         {
            writer.WriteLine("Sheild:" + sheild.Defence + "," + sheild.name + "," + sheild.description + "," + sheild.cost);
         }
      }     
   }
   else
   {}
}

I started using this code to load it but i don’t know how to finish the code. Right now its split but i don’t know how to assign it to anything.

For example sheild:20,Shield,this is a shield,100

Right now that’s split into

  1. 20,
  2. Shield,
  3. this is a shield,
  4. 100

But I don’t know who to assign those stuff to an array

public void Load()
{
   StreamReader reader;
   reader = new StreamReader("PlayerInventory.txt");
   string line;
   string[] currentLineData;

   while (true)
   {
      try
      {
         line = reader.ReadLine();
         if (line == null)
         {
            break;
         }
         if (line.Contains("Sheild"))
         {
            line.Replace("Sheild:", "");
            currentLineData = line.Split(',');
         }
      } 
      catch
      {
         break;
      }
}
reader.Close();}

One Answer

it looks like you are designing a game.

If I were setting up an inventory that included a shield with stats, I'd look at creating a complex data type, using a "struct" for an inventory item.

Then I'd create an array of the inventory struct items, with one for each inventory slot - before loading my file in.

This could hold all the different info you need for any item that can be stored in inventory like Item Name, defense strength, attack strength etc.

Then, when you load your file in, all the right stuff will be in places with nice names etc. for you to easily find them later.

If you need an extra stat, add a row to your struct definition, then add a column to your file and you are ready to go.

Answered by trevor on August 13, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP