Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by d112570 · May 17, 2014 at 05:59 PM · savearraylist

How do you save, read, edit an Arraylist (int).

I've got this integer array, already tried different methods I found on net, I only get permission issues.

Here is my array

 public static int [,,,,,] gridLocation = new int [10,10,10,10,27,7];
 public static string savePath;

Here I read and write to my gridLocation, each letter represent a number.

 gridLocation[g,s,p,m,b,a] = 4;
 print ("Read #" + gridLocation[g,s,p,m,b,a]);  // results will be 4.

Here is my savegame path

 var values = System.Enum.GetValues( typeof( System.Environment.SpecialFolder ));
 savePath = System.Environment.GetFolderPath((System.Environment.SpecialFolder)values.GetValue(3));
 print(savePath + "/Beyond.sav"); // results will be /Users/yourname/Beyond.sav

I would like to create a new save file, and once created - when 1 int is changed then only this int will be edited. And when opening the game this game save will be loading into the game and editing will continue during game save.

Comment
Add comment · Show 6
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image d112570 · May 19, 2014 at 01:10 PM 0
Share

Anyone? I need to create a new saved file on disk, and then edit a single data in the array. I would be reading the data, changing it, possible delete the whole saved file if user wishes it. There are no examples of this sort on the net, been looking for 2 days now.

avatar image BlackHoleStorm · May 19, 2014 at 01:17 PM 0
Share

Look at the online lessons, then look up the saving and loading data lesson. All you need to do is change the directory where it saves to where-ever you want to save it to.

avatar image tw1st3d · May 19, 2014 at 01:33 PM 0
Share

Dunno what kind of errors this may throw, but this is a little something I threw together.

 using UnityEngine;
 using System;
 using System.IO;
 using System.Collections;
 using System.Collections.Generic;
 
 public class SaveHandler : $$anonymous$$onoBehavior
 {
     // Store save directory and filename
     private string fileDirectory = "/Users/savegames/";
     private string username = "";
     
     // Save list of ints
     private List<int> saveList = new List<int>();
     
     void Start()
     {
         for(int i = 5; i += 7; i < 100) {
             // Generate some random ints
             this.saveList.Add(i);
         }
     }
     
     void Update()
     {
         if(Input.Get$$anonymous$$ey.$$anonymous$$eyCode("S")) {
             // If S, save
             saveGame(this.username);
             
             // If L, load
             loadGame(this.username);
             
             // If D, delete
             deleteGame(this.username);
         }
     }
     
     void OnGUI()
     {
         // Create text-field to set filename
         this.username = GUI.TextArea(new Rect(20, 20, 200, 20), this.username);
     }
     
     private void deleteGame(string filename)
     {
         if(File.Exists(this.fileDirectory + filename)) {
             // Delete file
             File.Delete(this.fileDirectory + filename);
             Debug.Log("File deleted");
         } else {
             Debug.Log("File doesn't exists");
         }
     }
     
     private void loadGame(string filename)
     {
         if(File.Exists(this.fileDirectory + filename)) {
             // If file exists, load file contents and parse into int list
             string fileContents = File.ReadAllLines(this.fileDirectory + filename);
             this.saveList = fileContents.Split(',').Select(int.Parse).ToList();
             
             // Log contents
             Debug.Log(fileContents);
         } else {
             Debug.Log("File does not exist.");
         }
     }
     
     private void saveGame(string filename)
     {
         // If the file exists,
         if(File.Exists(this.fileDirectory + filename)) {
             // Convert int list to comma separated string
             File.WriteAllLines(this.fileDirectory + filename, 
                                 string.Join(",", this.saveList.Select(i => i.toStrng()).toArray()));
         } else {
             // If it doesn't exists, create the file and re-run
             File.Create(this.fileDirectory + filename);
             saveFile(filename);
         }
     }
 }


This should generate a save with a result of something like 5,12,19,26,33 etc. Good luck, hope this helped.

avatar image d112570 tw1st3d · May 20, 2014 at 09:06 PM 0
Share

Still working on it, but this spits out an error at line 18.

 for(int i = 5; i += 7; i < 100) { // Only assignment, call, expressions, and object can be used as a statement.

Edit; Ok, your $$anonymous$$onoBehaviour was spelled wrong too, got that fixed. $$anonymous$$ore errors popped up since the fix.

 if(Input.Get$$anonymous$$ey.$$anonymous$$eyCode("S")) { // Expression denotes a method group where a variable, value , type was expected.

change it to if(Input.Get$$anonymous$$ey("S")) { // Now tons more errors show, in the load and save game errors 6 lines of error including for loop. I am unable to fix these cause this is unfamiliar ground for me. Please copy and paste this in your unity and test it.

avatar image d112570 tw1st3d · May 21, 2014 at 03:10 PM 0
Share

Can anyone fix tw1st3d code? Changed saveFile to saveGame, renamed $$anonymous$$onoBehaviour, renamed ToString() and ToArray(). Here I tried to fix everything I can. I added comments to where the errors are. I currently have 7 errors in this code.

 using UnityEngine;
 using System;
 using System.IO;
 using System.Collections;
 using System.Collections.Generic;
 
 public class SaveData : $$anonymous$$onoBehaviour
 {
     // Store save directory and filename
     private string path     = "Save";
     private string username = "$$anonymous$$";
     
     // Save list of ints
     private List<int> saveList = new List<int>();
     
     void Start()
     {
         for(int i = 5; i <= 10; ++i) saveList.Add(i); // Replaced random number, could not fix it.
         }
 
     void Update()
     {
         if(Input.Get$$anonymous$$ey("S"))   saveGame(username);
         if(Input.Get$$anonymous$$ey("L"))   loadGame(username);
         if(Input.Get$$anonymous$$ey("D")) deleteGame(username);
     }
 
     private void deleteGame(string filename) // Delete file
     {
         if(File.Exists(path + filename)) {
             File.Delete(path + filename);
             Debug.Log("File deleted"); 
         }
         else Debug.Log("File doesn't exists");
     }
     
     private void loadGame(string filename)
     {
         if(File.Exists(path + filename)) { // If file exists, load file contents and parse into int list
             string fileContents = File.ReadAllLines(path + filename); // Error - Cannot convert String[] to String
             saveList = fileContents.Split(',').Select(int.Parse).ToList(); //Error - does not recognize Select
             Debug.Log(fileContents);
         } else Debug.Log("File does not exist.");
     }
     
     private void saveGame(string filename)
     {
         // If the file exists,
         if(File.Exists(path + filename)) {
             // Convert int list to comma separated string
             File.WriteAllLines(path + filename, string.Join(",", saveList.Select(i => i.ToString()).ToArray())); // Error - Select bug and invalid arguments
         }
         else {
             // If it doesn't exists, create the file and re-run
             File.Create(path + filename);
             saveGame(filename);
         }
     }
 }
avatar image tw1st3d tw1st3d · May 21, 2014 at 06:38 PM 0
Share

I'll actually put this into the editor, and fix it up for you. However, it'd be better if you figured out how to solve each error, one at a time. Solving is learning.

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by d112570 · May 22, 2014 at 10:25 AM

OK got my multi dimensional list to format, save and read.

 public class Setup : MonoBehaviour {
      MyScript.setupGridList(0,0,0,0,0,0,0,0); // 0 = Format Grid (New)
      MyScript.setupGridList(1,1,4,3,1,1,1,5); // 1 = Write to Grid Location (Save)
      MyScript.setupGridList(2,1,4,3,1,1,1,0); // 2 = Read from Grid Location (Load)
 }

and the main coding area

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

 public class MyScript : MonoBehaviour {

   public static void setupGridList (int type, int g, int s, int p, int m, int b, int a, int grid) {
     if (type == 0) {
         // Resets Grid List to 0
         for (g = 0; g <=9; g++){ // Galaxy (g)
             for (s = 0; s <=9; s++){ // Star (s)
                 for (p = 0; p <=9; p++){ // Planet (p)
                     for (m = 0; m <=9; m++){ // Satellite (m)
                         for (b = 0; b <=26; b++){ // GridBox (b)
                             for (a = 0; a <=6; a++){ // Area (a)
                                 gridLocation[g,s,p,m,b,a] = 0;
                             }}}}}}}
     if (type == 1) { // 1 = Write to Grid
         gridLocation[g,s,p,m,b,a] = grid;
         var path = Application.dataPath + "/Save";
         if (!Directory.Exists (path)) Directory.CreateDirectory(path);
         using(StreamWriter sw = new StreamWriter(path + "/Beyond.txt")) foreach(var item in gridLocation) sw.WriteLine(item);
     }

     if (type == 2) { // 1 = Read Grid
         var path = Application.dataPath + "/Save";
         if (!Directory.Exists (path)) Directory.CreateDirectory(path);
         using(StreamReader sr = new StreamReader(path + "/Beyond.txt"))
         for (int gT = 0; gT <=9; gT++){ // Galaxy (g)
             for (int sT = 0; sT <=9; sT++){ // Star (s)
                 for (int pT = 0; pT <=9; pT++){ // Planet (p)
                     for (int mT = 0; mT <=9; mT++){ // Satellite (m)
                         for (int bT = 0; bT <=26; bT++){ // GridBox (b)
                             for (int aT = 0; aT <=6; aT++){ // Area (a)
                                 gridLocation[gT,sT,pT,mT,bT,aT] = int.Parse(sr.ReadLine());
         }}}}}}}}

For user data like name, resource amount etc I will use a different save since it will contain strings and integers, I will use the code from above with a little change. Thx for all your help.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by tw1st3d · May 21, 2014 at 06:53 PM

Fixed up code from comments, just to keep the answer clean. Hasn't been tested, but it throws no errors in the Unity editor. You'll have to figure out any further issues yourself. (challenge!)

 using UnityEngine;
 using System;
 using System.IO;
 using System.Linq;
 using System.Collections;
 using System.Collections.Generic;
 
 public class SaveData : MonoBehaviour
 {
     // Store save directory and filename
     private string path = "Save";
     private string username = "David";
     private static int saveListIdTotal = 32; // There will be a list of 32 numbers
     // Save list of ints
     private List<int> saveList = new List<int>(SaveData.saveListIdTotal);
 
     void Start()
     {
         for(int i = 5; i <= 10; ++i) saveList.Add(i); // Replaced random number, could not fix it.
     }
     
     void Update()
     {
         if(Input.GetKey(KeyCode.S)) saveGame(username);
         if(Input.GetKey(KeyCode.L)) loadGame(username);
         if(Input.GetKey(KeyCode.D)) deleteGame(username);
     }
     
     private void deleteGame(string filename) // Delete file
     {
         if(File.Exists(path + filename)) {
             File.Delete(path + filename);
             Debug.Log("File deleted");
         }
         else Debug.Log("File doesn't exists");
     }
     
     private void loadGame(string filename)
     {
         if(File.Exists(path + filename)) { // If file exists, load file contents and parse into int list
             string[] fileContents = File.ReadAllLines(path + filename); 
             foreach(string i in fileContents) {
                 this.saveList.Add(Int32.Parse(i));
             }
             Debug.Log(fileContents);
         } else Debug.Log("File does not exist.");
     }
     
     private void saveGame(string filename)
     {
         // If the file exists,
         if(File.Exists(path + filename)) {
             // Convert int list to comma separated string
             string filePath = "" + this.path + "" + filename + ""; // Safeguarding cause I didn't feel like making sure
             string[] contents = new string[1];
             contents[0] = string.Join(",", saveList.Select(i => i.ToString()).ToArray());
             File.WriteAllLines("" + filePath, contents);
         }
         else {
             // If it doesn't exists, create the file and re-run
             File.Create(path + filename);
             saveGame(filename);
         }
     }
 }
Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image tw1st3d · May 21, 2014 at 06:55 PM 0
Share

Ugh. Updated.

avatar image d112570 · May 21, 2014 at 08:35 PM 0
Share

Ok, had another error, Permission error, but I had it fixed when I changed

 private string username = "$$anonymous$$";

to

 private string username = "/$$anonymous$$.txt";

Works now. If file is missing it spits out 2 errors but it creates the missing file without data, press save again no errors. that is something I can figure out myself. Now I have the challenge of creating a multi array using somewhat the formula above.

I was wondering how would you generate random numbers in the for loop? Your code didn't work. I not going to use it, but it is very interesting to know for later use. Your help was very appreciated.

avatar image tw1st3d · May 21, 2014 at 09:29 PM 0
Share
 // Based on current code
 
 void Start()
 {
     int $$anonymous$$ = 0;    // Lowest number
     int max = 20;    // Highest number
     
     for(int i = 0; i < SaveData.saveListIdTotal; i++) {
         Random rnd = new Random();
         this.saveList.Add(rnd.Next($$anonymous$$, max)); 
         // creates a number between 0 and 20
     }
 }


As for the original, I feel like an idiot for ever putting what I did. This is fixed:

 for(int i = 5; i < 100; i += 7) {

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

22 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

"If there is no save data" or "If there are no PlayerPrefs" 2 Answers

save runtime created mesh class 0 Answers

PlayerPrefs and own Class 1 Answer

Player object carried from scene to scene 1 Answer

Unique ID Assignment 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges