-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
BetterPrefs.cs
930 lines (749 loc) · 27.9 KB
/
BetterPrefs.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
/*
BetterPrefs is a replacement for Unity's PlayerPrefs that aims to add features that PlayerPrefs is lacking, such as support for multiple saves, save import/export and even more data types, such as booleans, Vector2s and Vector3s.
Version: 3.0.0
https://github.com/Carroted/BetterPrefs
Author: amytimed
License: MIT
*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System;
public static class BetterPrefs
{
public static string saveLocation = Application.persistentDataPath + "/saves/"; // Set this to wherever you want your saves to be stored. In portable builds, you could use Application.dataPath + "/saves/". (makes saves in the same folder as the executable, like for storing games on a flash drive)
public static string saveExtension = ".sav"; // Set this to the extension you want your saves for your game to have.
public static string defaultSaveName = "game"; // The saves created by Set functions (like SetBool, SetFloat etc) will be, by default, saved to a file with this name.
static Dictionary<string, object> data; // The data that will be saved. This should only ever be accessed through the Get and Set functions.
public static string currentSave = null; // The full path and name of the save file that is currently loaded, null if no save is loaded.
static void Write2DArray(string[,] array, BinaryWriter writer) // Used by Save
{
writer.Write(array.GetLength(0));
writer.Write(array.GetLength(1));
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
writer.Write(array[i, j]);
}
}
// Close the writer
writer.Close();
}
static string[,] Read2DArray(BinaryReader reader) // Used by Load
{
int x = reader.ReadInt32();
int y = reader.ReadInt32();
string[,] array = new string[x, y];
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
array[i, j] = reader.ReadString();
}
}
// Close the reader
reader.Close();
return array;
}
public static void SetBool(string key, bool value)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return;
}
data[key] = value;
}
public static void SetInt(string key, int value)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return;
}
data[key] = value;
}
public static void SetFloat(string key, float value)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return;
}
if (key != "date")
{
data[key] = value;
}
else
{
Debug.LogError("BetterPrefs: Key \"date\" is reserved for the date of the save file. Please use a different key.");
}
}
public static void SetString(string key, string value)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return;
}
data[key] = value;
}
public static void SetVector2(string key, Vector2 value)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return;
}
data[key] = value;
}
public static void SetVector3(string key, Vector3 value)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return;
}
data[key] = value;
}
public static bool GetBool(string key, bool fallback)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return false;
}
if (data.ContainsKey(key))
{
return (bool)data[key];
}
else
{
return fallback;
}
}
public static int GetInt(string key, int fallback)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return -1;
}
if (data.ContainsKey(key))
{
return (int)data[key];
}
else
{
return fallback;
}
}
public static float GetFloat(string key, float fallback)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return -1;
}
if (data.ContainsKey(key))
{
return (float)data[key];
}
else
{
return fallback;
}
}
public static string GetString(string key, string fallback)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return "";
}
if (data.ContainsKey(key))
{
return ((string)data[key]);
}
else
{
return fallback;
}
}
public static Vector2 GetVector2(string key, Vector2 fallback)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return Vector2.zero;
}
if (data.ContainsKey(key))
{
return (Vector2)data[key];
}
else
{
return fallback;
}
}
public static Vector3 GetVector3(string key, Vector3 fallback)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return Vector3.zero;
}
if (data.ContainsKey(key))
{
return (Vector3)data[key];
}
else
{
return fallback;
}
}
// Get methods without fallback
public static bool GetBool(string key)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return false;
}
if (data.ContainsKey(key))
{
return (bool)data[key];
}
else
{
Debug.LogError("BetterPrefs: Key " + key + " does not exist. You should always use BetterPrefs.HasKey to check if a key exists before trying to access it.");
return false;
}
}
public static int GetInt(string key)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return -1;
}
if (data.ContainsKey(key))
{
return (int)data[key];
}
else
{
Debug.LogError("BetterPrefs: Key " + key + " does not exist. You should always use BetterPrefs.HasKey to check if a key exists before trying to access it.");
return -1;
}
}
public static float GetFloat(string key)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return -1;
}
if (data.ContainsKey(key))
{
return (float)data[key];
}
else
{
Debug.LogError("BetterPrefs: Key " + key + " does not exist. You should always use BetterPrefs.HasKey to check if a key exists before trying to access it.");
return -1;
}
}
public static string GetString(string key)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return "";
}
if (data.ContainsKey(key))
{
return ((string)data[key]);
}
else
{
Debug.LogError("BetterPrefs: Key " + key + " does not exist. You should always use BetterPrefs.HasKey to check if a key exists before trying to access it.");
return "";
}
}
public static Vector2 GetVector2(string key)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return Vector2.zero;
}
if (data.ContainsKey(key))
{
return (Vector2)data[key];
}
else
{
Debug.LogError("BetterPrefs: Key " + key + " does not exist. You should always use BetterPrefs.HasKey to check if a key exists before trying to access it.");
return Vector2.zero;
}
}
public static Vector3 GetVector3(string key)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return Vector3.zero;
}
if (data.ContainsKey(key))
{
return (Vector3)data[key];
}
else
{
Debug.LogError("BetterPrefs: Key " + key + " does not exist. You should always use BetterPrefs.HasKey to check if a key exists before trying to access it.");
return Vector3.zero;
}
}
public static string Save(string savePath = "default")
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return null;
}
if (savePath == "default")
{
savePath = currentSave; // If no save path is specified, we save to where our loaded save is located. This is useful for saving over the same save file.
}
// Data is stored in a two-dimensional array of strings. They contain the type, key and value of each entry.
/* Example:
{
{ "int", "exampleInt", "2" },
{ "string", "exampleString", "Hello World!"},
{ "vector2", "exampleVector2", "1.0,2.0" },
{ "bool", "exampleBool", "true" }
}
*/
// Add the current date and time to the array (UNIX time)
double totalSecs = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
data["date"] = (float)totalSecs; // Set the date key to the current time now that we know at what time the save was made
string[,] dataArray = new string[data.Count, 3];
if (data.Count == 0)
{
// Delete save file if it exists
if (File.Exists(savePath))
{
File.Delete(savePath);
}
Debug.Log("BetterPrefs: Saved file with no data; deleted file");
return null;
}
int i = 0; // Using a foreach loop with an index is actually simpler than using a for loop for this very specific case.
foreach (KeyValuePair<string, object> pair in data)
{
// Add the stuff to the array
string objectType = "unknown";
string valueFormatted = "unparsable";
if (pair.Value is bool)
{
objectType = "bool";
valueFormatted = pair.Value.ToString().ToLower();
}
else if (pair.Value is int)
{
objectType = "int";
valueFormatted = pair.Value.ToString();
}
else if (pair.Value is float)
{
if (pair.Key != "date")
{
objectType = "float";
valueFormatted = pair.Value.ToString();
}
else
{
objectType = "float";
valueFormatted = totalSecs.ToString(); // override the date value with the current time
}
}
else if (pair.Value is string)
{
objectType = "string";
valueFormatted = pair.Value.ToString();
}
else if (pair.Value is Vector2)
{
objectType = "vector2";
Vector2 value = (Vector2)pair.Value;
valueFormatted = value.x.ToString() + "," + value.y.ToString();
}
else if (pair.Value is Vector3)
{
objectType = "vector3";
Vector3 value = (Vector3)pair.Value;
valueFormatted = value.x.ToString() + "," + value.y.ToString() + "," + value.z.ToString();
}
else
{
Debug.LogError("BetterPrefs: Unsupported type " + pair.Value.GetType() + " for key " + pair.Key);
continue;
}
dataArray[i, 0] = objectType;
dataArray[i, 1] = pair.Key;
dataArray[i, 2] = valueFormatted;
i++;
}
// Save the data to the file
// If any of the directories in savePath don't exist, create them
Directory.CreateDirectory(Path.GetDirectoryName(savePath));
// Use Write2DArray we defined earlier to write the data to the file
FileStream file = File.Create(savePath);
// Write2DArray(string[,], BinaryWriter)
Write2DArray(dataArray, new BinaryWriter(file));
file.Close();
Debug.Log("BetterPrefs: Saved data to \"" + savePath + "\"");
return savePath; // Return the path to the file, could be useful
}
public static void Load(string savePath = "default")
{
if (savePath == "default")
{
savePath = Path.Combine(saveLocation, defaultSaveName, saveExtension); // If no save path is specified, we load from the default save file.
}
data = new Dictionary<string, object>();
if (File.Exists(savePath)) // If the file doesn't exist, we know that file path is where the current save should be, so we store that and when Save is called, saves will be put there by default.
{
// Use Read2DArray we defined earlier to read the data from the file
FileStream file = File.Open(savePath, FileMode.Open);
// Read2DArray(BinaryReader)
string[,] dataArray = Read2DArray(new BinaryReader(file));
file.Close();
// Add the data from the array to the dictionary
for (int i = 0; i < dataArray.GetLength(0); i++)
{
string objectType = dataArray[i, 0];
string key = dataArray[i, 1];
string valueFormatted = dataArray[i, 2];
if (objectType == "bool")
{
// This is a bool
bool value;
if (bool.TryParse(valueFormatted, out value))
{
// The value is a valid bool
}
else
{
// The value is not a valid bool
Debug.LogWarning("BetterPrefs: Invalid bool value in save file \"" + savePath + "\" for key \"" + key + "\"");
continue;
}
// Add the value to the dictionary
if (!data.ContainsKey(key))
{
data.Add(key, value);
}
else
{
Debug.LogWarning("BetterPrefs: Duplicate key in save file \"" + savePath + "\" " + key + ". Using the last one.");
data[key] = value;
}
}
else if (objectType == "string")
{
// This is a string
string value = valueFormatted; // :D :) :D :D
// Add the value to the dictionary
if (!data.ContainsKey(key))
{
data.Add(key, value);
}
else
{
Debug.LogWarning("BetterPrefs: Duplicate key in save file \"" + savePath + "\" " + key + ". Using the last one.");
data[key] = value;
}
}
else if (objectType == "int")
{
// This is an int
int value;
if (int.TryParse(valueFormatted, out value))
{
// The value is a valid int
}
else
{
// The value is not a valid int
Debug.LogWarning("BetterPrefs: Invalid int value in save file \"" + savePath + "\" for key \"" + key + "\"");
continue;
}
// Add the value to the dictionary
if (!data.ContainsKey(key))
{
data.Add(key, value);
}
else
{
Debug.LogWarning("BetterPrefs: Duplicate key in save file \"" + savePath + "\" " + key + ". Using the last one.");
data[key] = value;
}
}
else if (objectType == "float")
{
// This is a float
float value;
if (float.TryParse(valueFormatted, out value))
{
// The value is a valid float
}
else
{
// The value is not a valid float
Debug.LogWarning("BetterPrefs: Invalid float value in save file \"" + savePath + "\" for key \"" + key + "\"");
continue;
}
// Add the value to the dictionary
if (!data.ContainsKey(key))
{
data.Add(key, value);
}
else
{
Debug.LogWarning("BetterPrefs: Duplicate key in save file \"" + savePath + "\" " + key + ". Using the last one.");
data[key] = value;
}
}
else if (objectType == "vector2")
{
// This is a vector2
Vector2 value;
// There is no TryParse for Vector2, so we have to do it manually
float x;
float y;
string[] values = valueFormatted.Split(',');
if (values.Length != 2)
{
// There is more than one comma in the value, so it is not a valid vector2
Debug.LogWarning("BetterPrefs: Invalid vector2 value in save file \"" + savePath + "\" for key \"" + key + "\"");
continue;
}
else
{
if (float.TryParse(values[0].Trim(), out x))
{
// The x value is a valid float
}
else
{
// The x value is not a valid float
Debug.LogWarning("BetterPrefs: Invalid vector2 X value in save file \"" + savePath + "\" for key \"" + key + "\"");
continue;
}
if (float.TryParse(values[1].Trim(), out y))
{
// The y value is a valid float
}
else
{
// The y value is not a valid float
Debug.LogWarning("BetterPrefs: Invalid vector2 Y value in save file \"" + savePath + "\" for key \"" + key + "\"");
continue;
}
// Add the value to the dictionary
value = new Vector2(x, y);
if (!data.ContainsKey(key))
{
data.Add(key, value);
}
else
{
Debug.LogWarning("BetterPrefs: Duplicate key in save file \"" + savePath + "\" " + key + ". Using the last one.");
data[key] = value;
}
}
}
else if (objectType == "vector3")
{
// This is a vector3
Vector3 value;
// There is no TryParse for Vector3, so we have to do it manually
float x;
float y;
float z;
string[] values = valueFormatted.Split(',');
if (values.Length != 3)
{
// There is more than one comma in the value, so it is not a valid vector3
Debug.LogWarning("BetterPrefs: Invalid vector3 value in save file \"" + savePath + "\" for key \"" + key + "\"");
continue;
}
else
{
if (float.TryParse(values[0].Trim(), out x))
{
// The x value is a valid float
}
else
{
// The x value is not a valid float
Debug.LogWarning("BetterPrefs: Invalid vector3 X value in save file \"" + savePath + "\" for key \"" + key + "\"");
continue;
}
if (float.TryParse(values[1].Trim(), out y))
{
// The y value is a valid float
}
else
{
// The y value is not a valid float
Debug.LogWarning("BetterPrefs: Invalid vector3 Y value in save file \"" + savePath + "\". for key \"" + key + "\"");
continue;
}
if (float.TryParse(values[2].Trim(), out z))
{
// The z value is a valid float
}
else
{
// The z value is not a valid float
Debug.LogWarning("BetterPrefs: Invalid vector3 Z value in save file \"" + savePath + "\" for key \"" + key + "\"");
continue;
}
// Add the value to the dictionary
value = new Vector3(x, y, z);
if (!data.ContainsKey(key))
{
data.Add(key, value);
}
else
{
Debug.LogWarning("BetterPrefs: Duplicate key in save file \"" + savePath + "\" " + key + ". Using the last one.");
data[key] = value;
}
}
}
else if (objectType == "unknown")
{
Debug.LogWarning("BetterPrefs: A type of unknown was found in save file \"" + savePath + "\". This is caused by BetterPrefs.Save encountering an unsupported type in its data. Please do not manually edit BetterPrefs data from memory without using BetterPrefs methods.");
}
else
{
// This is not a valid type
Debug.LogWarning("BetterPrefs: Invalid type in save file \"" + savePath + "\" for key \"" + key + "\"");
continue;
}
}
}
currentSave = savePath;
}
public static void DeleteAll()
{
// Delete all the data
if (data == null)
{
data = new Dictionary<string, object>();
}
data.Clear();
Debug.Log("BetterPrefs: Deleted all data (this can be undone by quitting without saving)");
}
public static void DeleteKey(string key)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return;
}
// Delete the key
data.Remove(key);
}
public static bool HasKey(string key)
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return false;
}
// Check if the key exists
return data.ContainsKey(key);
}
public static DateTime GetDate(string savePath = "current") // Get the date of a save, or, if the save wasn't saved yet, the current date
{
if (savePath == "current")
{
if (HasKey("date"))
{
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds((int)GetFloat("date"));
return dateTimeOffset.LocalDateTime;
}
else
{
return DateTime.Now;
}
}
else
{
if (!File.Exists(savePath))
{
Debug.LogWarning("BetterPrefs: The save file \"" + savePath + "\" does not exist");
return DateTime.Now;
}
// Get the date from the save file using Read2DArray
FileStream file = File.Open(savePath, FileMode.Open);
BinaryReader reader = new BinaryReader(file);
string[,] dataArray = Read2DArray(reader);
file.Close();
for (int i = 0; i < dataArray.GetLength(0); i++)
{
string objectType = dataArray[i, 0];
string key = dataArray[i, 1];
string valueFormatted = dataArray[i, 2];
if (key == "date")
{
if (objectType == "float")
{
// This is a float
float value;
if (float.TryParse(valueFormatted, out value))
{
// The value is a valid float
}
else
{
// The value is not a valid float
Debug.LogWarning("BetterPrefs: Invalid date in save file \"" + savePath + "\"");
continue;
}
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds((int)value);
return dateTimeOffset.LocalDateTime;
}
}
}
Debug.LogError("BetterPrefs: Could not find the date in the save file");
return DateTime.MinValue;
}
}
public static int GetCount() // Get how many keys are in the data
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return -1;
}
return data.Count;
}
public static Dictionary<string, object> GetData() // Get the data
{
if (data == null)
{
Debug.LogError("BetterPrefs: No save is loaded, but you are trying to access it");
return new Dictionary<string, object>();
}
return data;
}
}