The isActive bool is not loaded. It saved. The bool is supposed to be loaded on my glyph list. why is it not the case?
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
[System.Serializable]
public class GameData
{
public int character;
public float health;
public float stamina;
public float flashlightAmount;
public int ammo;
public float fearLevel;
public float sanityLevel;
public bool insaneMode;
public int trainDestroyed;
public int deathCount;
public int headShot;
public int fatalHeadShot;
public int numberOfItems;
public int numberOfContainerItems;
public Vector3 playerPosition;
public bool quest1;
public bool quest2;
public bool quest3;
public SerializableDictionary<string, bool> enemiesKilled;
public SerializableDictionary<string, bool> itemsCollected;
public SerializableDictionary<string, bool> narrativeDestroyed;
public InventoryManager.Currency currency;
public List items = new List();
public List containers = new List();
public List containers1 = new List();
public List containers2 = new List();
public List containers3 = new List();
public List containers4 = new List();
public List containers5 = new List();
code
public List<LovecraftianPuzzle.EldritchSymbols> currentOrder;
public SerializableDictionary<LovecraftianPuzzle.EldritchSymbols, bool> glyphsState;
//Options preferences
//Doors
//Mini events
public GameData()
{
character = menuScript1.PlayerSelected;
if (character == 1)
{
playerPosition = new Vector3(268.92f, 52.337f, 219.93f);
}
else if (character == 2)
{
playerPosition = new Vector3(-44.85f, 71.27088f, 108.83f);
}
else if (character == 3)
{
playerPosition = new Vector3(-44.85f, 71.27088f, 108.83f);
}
this.health = 100;
this.stamina = 100;
this.flashlightAmount = 100;
this.ammo = 0;
this.fearLevel = 0;
this.sanityLevel = 30;
this.insaneMode = false;
this.trainDestroyed = 0;
this.deathCount = 0;
this.headShot = 0;
this.fatalHeadShot = 0;
this.numberOfItems = 0;
this.numberOfContainerItems = 0;
enemiesKilled = new SerializableDictionary<string, bool>();
itemsCollected = new SerializableDictionary<string, bool>();
narrativeDestroyed = new SerializableDictionary<string, bool>();
currency= new InventoryManager.Currency();
currency.Name = "Gold";
items = new List<PlayerItemData>();
containers= new List<ContainerItemData>();
containers1 = new List<ContainerItemData>();
containers2 = new List<ContainerItemData>();
containers3 = new List<ContainerItemData>();
containers4 = new List<ContainerItemData>();
containers5 = new List<ContainerItemData>();
this.quest1 = false;
this.quest2 = false;
this.quest3 = false;
currentOrder = new List<LovecraftianPuzzle.EldritchSymbols>();
glyphsState = new SerializableDictionary<LovecraftianPuzzle.EldritchSymbols, bool>();
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LovecraftianPuzzle : MonoBehaviour, IDataPersistence
{
public enum EldritchSymbols { Nyarlathotep, Azathoth, Cthulhu, ShubNiggurath, YogSothoth }
public Transform[] symbolSlots;
public GameObject[] eldritchSymbolPrefabs;
public GameObject[] glyphsGameObject;
public List glyphs;
public List books;
public GameObject portal;
public Animator portalAnimator;
public AudioSource gatewayAudio;
public AudioClip placeSymbolSound;
public AudioClip puzzleSolvedSound;
public GameObject bookParticlePrefab;
public GameObject shadowPeoplePrefab;
private GameObject player;
private AudioSource playerAudioSource;
private InventoryManager InvManager;
private AudioSource puzzleAudio;
private FearSystem fearSystem;
private QuestSystem questSystem;
code
private void Start()
{
player = GameObject.Find("Player");
playerAudioSource = player.GetComponent<AudioSource>();
puzzleAudio = GetComponent<AudioSource>();
InvManager = FindAnyObjectByType(typeof(InventoryManager)) as InventoryManager;
fearSystem = FindAnyObjectByType(typeof(FearSystem)) as FearSystem;
questSystem = FindAnyObjectByType(typeof(QuestSystem)) as QuestSystem;
glyphs = new List<Glyphs>
{
new Glyphs { symbolType = EldritchSymbols.Nyarlathotep, symbolGlyph = glyphsGameObject[0], isActive = false},
new Glyphs { symbolType = EldritchSymbols.Azathoth,symbolGlyph = glyphsGameObject[1], isActive = false},
new Glyphs { symbolType = EldritchSymbols.Cthulhu, symbolGlyph = glyphsGameObject[2], isActive = false},
new Glyphs { symbolType = EldritchSymbols.ShubNiggurath, symbolGlyph = glyphsGameObject[3], isActive = false},
new Glyphs { symbolType = EldritchSymbols.YogSothoth, symbolGlyph = glyphsGameObject[4], isActive = false}
};
books = new List<Book>
{
new Book { title = "Invocations of The Cosmic Horror", symbolType = EldritchSymbols.Nyarlathotep, symbolPrefab = eldritchSymbolPrefabs[0] },
new Book { title = "Mark Of The Old Gods", symbolType = EldritchSymbols.Azathoth, symbolPrefab = eldritchSymbolPrefabs[1] },
new Book { title = "The House Of R'lyeh", symbolType = EldritchSymbols.Cthulhu, symbolPrefab = eldritchSymbolPrefabs[2] },
new Book { title = "The Shadow People", symbolType = EldritchSymbols.ShubNiggurath, symbolPrefab = eldritchSymbolPrefabs[3] },
new Book { title = "The Unknown and The Deep Void", symbolType = EldritchSymbols.YogSothoth, symbolPrefab = eldritchSymbolPrefabs[4] }
};
}
private List<EldritchSymbols> correctOrder = new List<EldritchSymbols>()
{
EldritchSymbols.Nyarlathotep,
EldritchSymbols.Azathoth,
EldritchSymbols.Cthulhu,
EldritchSymbols.ShubNiggurath,
EldritchSymbols.YogSothoth
};
public List<EldritchSymbols> currentOrder = new List<EldritchSymbols>();
private Dictionary<EldritchSymbols, int> symbolToSlotIndex = new Dictionary<EldritchSymbols, int>()
The issue might be related to data persistence between saving and loading sessions, particularly regarding the glyphsState within GameData. Here are some steps you can take to troubleshoot the problem:
Check Save and Load Logic: Ensure that the SaveData and LoadData methods are properly being called. Place debugging statements within these methods to confirm they execute correctly when saving and loading data.
Verify Glyph State Assignment: Debug the LoadData method to make sure that the glyph.isActive assignment is indeed being hit and that glyphData.Value is the expected boolean value.
Review Data Structure: Make sure that the SerializableDictionary is correctly serializable and that it preserves the data across runs. Unity's default serialization does not support dictionaries out-of-the-box, so if SerializableDictionary is a custom implementation, ensure it's being handled correctly. Check that the dictionary is populated correctly before the save and after the load.
Examine Object References: Ensure that the glyphs' GameObject references (glyph.symbolGlyph) are correctly maintained when loading the game state. GameObject references cannot directly be serialized and require special handling.
Confirm Data Integrity: Verify that the saved data file indeed contains the expected values for glyphsState. It's possible that an error might be occurring while saving, leading to incorrect loading later.
Inspect Glyphs' Activation: For the glyphs to display their active/inactive state properly, you might need to implement visual updates in the LoadData method similar to the commented UpdateGlyphDisplay. This function seems vital in toggling the actual GameObject's visibility or material properties, which might not be covered by just setting the isActive boolean.
Check for Overwrites: If anything else in your code modifies the glyph list or the dictionary after LoadData runs, it could overwrite the loaded values. Carefully check the game's flow to ensure that loaded values are not being accidentally overwritten.
Validate Scene State: If loading is happening during scene transitions or object instantiation, make sure all necessary game objects and components are present ("awake" or "started") when the function is called.
User
I'm setting a new list of glyph at start, like so :
glyphs = new List
{
new Glyphs { symbolType = EldritchSymbols.Nyarlathotep, symbolGlyph = glyphsGameObject[0], isActive = false},
new Glyphs { symbolType = EldritchSymbols.Azathoth,symbolGlyph = glyphsGameObject[1], isActive = false},
new Glyphs { symbolType = EldritchSymbols.Cthulhu, symbolGlyph = glyphsGameObject[2], isActive = false},
new Glyphs { symbolType = EldritchSymbols.ShubNiggurath, symbolGlyph = glyphsGameObject[3], isActive = false},
new Glyphs { symbolType = EldritchSymbols.YogSothoth, symbolGlyph = glyphsGameObject[4], isActive = false}
};
books = new List<Book
Do you think this could lead to make seem the load method is not working although it is?
Assistant
Yes, you have identified the likely problem. In the Start method of the LovecraftianPuzzle class, you're reinitializing the glyphs list every time the scene starts, setting all isActive boolean values to false. The reinitialization will override any loaded states if the LoadData method is called after this initialization block.
Here's one possible resolution:
Ensure that the LoadData method is called after the glyphs list has been initially populated. This requires that the code loading from saved data runs at the correct point in the startup sequence (for example, after all objects have been created but before user interaction or game logic commences). Unity's Start method is called on every active GameObject when it is initialized, so if your load process isn't happening until later, the glyphs list will reset.
If your loading process is connected to a scene load, and if the loading functionality is tied to the Start method (or an event triggered by the Start method), this issue will occur. The load should ideally happen in a method like Awake (which is called before Start) and should not repeat the initialization that was done in Start. Here's an example sequence to illustrate this:
csharp
private void Awake()
{
LoadData(someGameData); // Load the game data, where someGameData is your preloaded game data
}
private void Start()
{
InitGlyphs(); // Do the glyphs setup or any other configuration
}
Here, LoadData() loads the saved isActive states and sets the glyphs to their correct states before Start runs. Alternatively, you can add a condition in the Start method to only initialize the glyphs list if the data hasn't been loaded, or you could have a separate method to initialize glyphs only if necessary.
The key is to ensure the loading process gets the opportunity to set the state before any gameplay logic that might depend on that state has the chance to run.
User
I moved it inside the awake function and now the bool is loading up
Assistant
Great, moving the initialization into the Awake function was the correct approach. In Unity, the Awake function is called when the script instance is being loaded, prior to any Start methods called in the scene. This allows you to set up references and initial states before the game objects begin their main behavior.
By initializing your glyphs in Awake, you ensure that when your scene starts, all game objects and components are set up correctly before the first frame of the game. This also means that the LoadData method can be safely called afterwards and have its state applied correctly, without being overridden by the initial setup.
Just for further clarity, here's how the execution order looks now:
Awake(): Called when the script instance is loaded.
Initialize glyphs list and any other necessary setup here.
Start(): Called just before the first frame where the instance is enabled.
Perform any additional setup that doesn't involve initializing the glyphs list, since it's now already been initialized in Awake.
LoadData(): Called when loading saved states/data.
Apply saved game states to your already-initialized glyphs list.
By adhering to this order of operations, you ensure that all components are ready to receive and apply saved data without interference from other initial setup logic. Always remember to use Awake() for initial setup, and then use Start() for when you need to do operations that require all objects to be in place. And for loading saved game states, always do it after the initial setup is complete and consistent across sessions.
User
How can I use the isActive bool from each glyph to ensure there emission color is saved and loaded? Or, is it better to just create a function which handle wether or nor the emission is red(correct) or green(incorrect) according to their isActive bool true or false?
Assistant
Using the isActive boolean to determine the emission color of each glyph, and ensuring this state is saved and loaded correctly, is a good design practice. It keeps the logic for how glyphs should look centralized and makes it easier to manage their visual state consistently.
Since you already have the boolean isActive in the Glyphs class to represent the glyph's state, you can create functions that handle the visual update according to this state. Here's a high-level approach on how you can manage this:
Create a Function to Update Display: Implement a method that updates the visual display (emission color) of a glyph based on its isActive state.
csharp
private void UpdateGlyphDisplay(Glyphs glyph)
{
Color emissiveColor = glyph.isActive ? Color.red : Color.green; // Red for active(True), Green for inactive(False)
Material glyphMaterial = glyph.symbolGlyph.GetComponent<Renderer>().material;
glyphMaterial.SetColor("_EmissionColor", emissiveColor);
// You may need to modify the rendering mode for proper emission
// glyphMaterial.EnableKeyword("_EMISSION");
}
Call Update Function After Loading: In the LoadData method, once you've set the isActive state from the saved data, call this function to update the emission color of the glyph accordingly.
csharp
public void LoadData(GameData data)
{
// ... (other loading logic)
foreach (var glyphData in data.glyphsState)
{
var glyph = glyphs.Find(g => g.symbolType == glyphData.Key);
if (glyph != null)
{
glyph.isActive = glyphData.Value;
UpdateGlyphDisplay(glyph); // Update the visual state according to isActive
}
}
}
Call Update Function When State Changes: Whenever you change the state of isActive during gameplay (when a glyph is activated or deactivated), you should also call the to make sure the visual reflects this change.
User
It works, but only one renderer material is changing, because I have many of them. The following line should be changed :
Material glyphMaterial = glyph.symbolGlyph.GetComponentInChildren().material;
Assistant
You're correct; if a single glyph consists of multiple parts, each with its own renderer, you'll need to update the materials on all these renderers. You can adjust the UpdateGlyphDisplay() method to loop through all child renderers and apply the emission color to each material.
Here's how you can adapt the function:
csharp
private void UpdateGlyphDisplay(Glyphs glyph)
{
Color emissiveColor = glyph.isActive ? Color.red : Color.green; // Red for active(True), Green for inactive(False)
Renderer[] childRenderers = glyph.symbolGlyph.GetComponentsInChildren<Renderer>();
foreach (Renderer renderer in childRenderers)
{
Material glyphMaterial = renderer.material;
glyphMaterial.SetColor("_EmissionColor", emissiveColor);
glyphMaterial.EnableKeyword("_EMISSION");
}
}
This revised version of the function gets the array of Renderer components that are children of the symbolGlyph GameObject and then loops through each renderer to update the emission color of its material.
Please note that using the .material property creates an instance of the material. This is fine if you only update the materials infrequently. However, if you are updating materials every frame or very often, you might want to use .sharedMaterial instead to avoid creating new instances and causing a performance overhead.
Here's how you'd use .sharedMaterial:
csharp
private void UpdateGlyphDisplay(Glyphs glyph)
{
Color emissiveColor = glyph.isActive ? Color.red : Color.green; // Red for active(True), Green for inactive(False)
Renderer[] childRenderers = glyph.symbolGlyph.GetComponentsInChildren<Renderer>();
foreach (Renderer renderer in childRenderers)
{
Material glyphMaterial = renderer.sharedMaterial; // Use sharedMaterial to avoid creating material instances
glyphMaterial.SetColor("_EmissionColor", emissiveColor);
glyphMaterial.EnableKeyword("_EMISSION");
}
}
Using shared materials will ensure that if multiple renderers share a material, all their appearances will update at once, and you won't unnecessarily create new material instances. However, be cautious when changing shared materials during runtime, as this will affect all objects using this material, not just the current object's renderers.
Make sure all materials you're planning to change have emission enabled in their shader settings, and that the emission keyword is enabled for those materials. This is sometimes necessary to ensure that emission updates are rendered correctly.
User
Now that I can save and load the glyphs, how can I save and load the instantiated gameObject in the PlaceSymbol() function?
Assistant
Saving and loading instantiated GameObjects in Unity can be quite complex due to serialization limitations, especially for GameObjects created at runtime. Unity does not save the state of instantiated GameObjects automatically, so you need to manually save the necessary information and recreate the objects when you load the game.
Here's a general approach to save and load instantiated GameObjects like symbols in your PlaceSymbol() function:
Save:
Store Instance Information: Create a serializable class to store information about each instantiated symbol (e.g., type, position, rotation).
csharp
[System.Serializable]
public class SavedSymbol
{
public EldritchSymbols type;
public Vector3 position;
public Quaternion rotation;
}
Update GameData: Add a list of SavedSymbol to GameData to keep track of the instantiated symbols.
csharp
[System.Serializable]
public class GameData
{
// ... (existing fields)
public List<SavedSymbol> savedSymbols = new List<SavedSymbol>();
}
Capture State on Instantiate: Whenever you instantiate a symbol in PlaceSymbol(), create a SavedSymbol object and add it to your save data.
csharp
public void PlaceSymbol(EldritchSymbols symbol)
{
// ... (existing code)
SavedSymbol savedSymbol = new SavedSymbol
{
type = symbol,
position = symbolObject.transform.position,
rotation = symbolObject.transform.rotation
};
GameData.savedSymbols.Add(savedSymbol);
// ... (rest of the code)
}
Load:
Recreate Instances: During the load process, iterate over the list of saved symbols and instantiate them in the scene.
csharp
User
Maybe I can just check if I have a save with if (!DataPersistenceManager.Instance.HasGameData()), if there's one then check which symbolSlot is taken and by which symbol, if there's a symbol in a symbolSlot, instantiate the gameObject using the method in the PlaceSymbol function
Assistant
Yes, upon loading the scene, you can use data persistence to check if saved game data exists, and if so, use that data to determine which symbolSlot should contain what symbol. This approach involves checking the state of each symbolSlot after loading the game and creating the symbols accordingly.
Here's an outline of the steps you might take:
During Load
Check for saved game data.
If data exists, go through each saved symbol state.
For each saved state, instantiate the corresponding symbol GameObject at the saved position with the saved rotation.
Here is a representation of how you might implement this:
csharp
public void LoadGame()
{
if (DataPersistenceManager.Instance.HasGameData())
{
GameData data = DataPersistenceManager.Instance.LoadGame();
// Potentially clear the current scene of symbols before loading
// ClearCurrentSymbols();
// Loop through each saved symbol state and instantiate the necessary GameObjects
foreach (SavedSymbol savedSymbol in data.savedSymbols)
{
// Find the correct slot based on the loaded data (e.g., a symbol type to slot index mapping)
Transform symbolSlot = symbolSlots[savedSymbol.symbolSlotIndex];
// Check if the slot is already taken; if not, instantiate the symbol
if (symbolSlot.childCount == 0)
{
GameObject symbolPrefab = GetPrefabFromSymbolType(savedSymbol.type);
if (symbolPrefab != null)
{
// Instantiate symbol at the correct slot.
GameObject symbolObject = Instantiate(symbolPrefab, symbolSlot.position, symbolSlot.rotation, symbolSlot);
// If needed, handle additional steps to recreate the exact state
// (e.g., setting specific properties or component states).
}
}
}
}
}
User
I dont have any savedSymbols. What i do have though is a symbolSlots transform array. When it populates, i can track what's in the array and spawn the book
Assistant
Given that you have a symbolSlots transform array that tracks the positions where symbols (in the context of your game, they might be books) should be placed, you can indeed use this to recreate the state of your puzzle when loading the game. Here's a generalized idea of how you could achieve this based on the currentOrder which determines the placed symbols' order:
During Save
For each symbol slot, save the type of symbol that is present (if any). Given your currentOrder seems to be tracking the order of placed symbols, make sure the GameData also keeps track of which symbol is in which slot.
csharp
[System.Serializable]
public class GameData
{
// ... (other fields)
public List<EldritchSymbols?> symbolSlotsState = new List<EldritchSymbols?>(); // Nullable to allow for empty slots
}
During save, store the EldritchSymbols type in the corresponding index of symbolSlotsState or null if a slot is empty.
csharp
public void SaveData(GameData data)
{
// ... (other saving logic)
for (int i = 0; i < symbolSlots.Length; ++i)
{
if (symbolSlots[i].childCount > 0)
{
EldritchSymbol symbol = symbolSlots[i].GetChild(0).GetComponent<EldritchSymbol>();
data.symbolSlotsState[i] = symbol.symbolType;
}
else
{
data.symbolSlotsState[i] = null; // Slot is empty
}
}
// ... (save other game states to data)
}
During Load
When loading, check the symbolSlotsState list to see what should be in each symbolSlot. If there is an EldritchSymbols entry that is not null, instantiate and place the appropriate book.
csharp
User
GetPrefabFromSymbolType does not exist in the actual context
Assistant
Apologies for the earlier confusion. The function GetPrefabFromSymbolType is a placeholder for a function you would need to implement that returns the corresponding prefab GameObject based on a given EldritchSymbols type. The idea is to map each symbol type to its respective prefab so that you can instantiate it during the loading process.
Here's how you could implement such a function within your managing script. First, set up a simple way to link the EldritchSymbols to their corresponding prefabs, using a dictionary, for example:
csharp
private Dictionary<EldritchSymbols, GameObject> symbolPrefabsMap;
private void Awake()
{
symbolPrefabsMap = new Dictionary<EldritchSymbols, GameObject>
{
{ EldritchSymbols.Nyarlathotep, nyarlathotepPrefab },
{ EldritchSymbols.Azathoth, azathothPrefab },
{ EldritchSymbols.Cthulhu, cthulhuPrefab },
// ... and so on for the rest of the symbols
};
}
For this to work, you would need to define the prefab variables (nyarlathotepPrefab, azathothPrefab, etc.) and link them through the Unity Inspector or by loading them from Resources or any other method you're using to reference prefabs.
Then, implement the GetPrefabFromSymbolType function:
csharp
private GameObject GetPrefabFromSymbolType(EldritchSymbols symbolType)
{
if (symbolPrefabsMap.TryGetValue(symbolType, out GameObject prefab))
{
return prefab;
}
else
{
Debug.LogError("Prefab not found for symbol type: " + symbolType);
return null;
}
}
Now you can use this function to get the correct prefab based on the EldritchSymbols type stored in your saved game data:
csharp
public void LoadData(GameData data)
{
// ... (other load logic)
for (int i = 0; i < data.symbolSlotsState.Count; ++i)
{
EldritchSymbols? symbolType = data.symbolSlotsState[i];
if (symbolType.HasValue)
{
GameObject symbolPrefab = GetPrefabFromSymbolType(symbolType.Value);
if (symbolPrefab != null)
{
Instantiate(symbolPrefab, symbolSlots[i].position, Quaternion.identity, symbolSlots[i]);
}
}
}
// ... (other load states)
}
With this in place, GetPrefabFromSymbolType will map the EldritchSymbols value to a prefab GameObject which you can then instantiate. This function would live inside the same script where you're dealing with saving and loading logic related to these symbols.
User
I have this dictionnary in the script already, can it be useful ?
The existing dictionary that maps EldritchSymbols to slot indexes can indeed be useful for keeping track of what belongs in each slot, but it seems to serve a slightly different purpose. This dictionary maps each symbol to a specific slot index, likely for the purpose of knowing where to place each symbol based on the type.
However, to instantiate the correct prefab based on a symbol type during the loading process, you still need a separate mapping from EldritchSymbols to their corresponding prefab GameObjects.
If you have prefab references in your script or linked through the Unity Inspector, you can create a new mapping similar to the following:
csharp
private Dictionary<EldritchSymbols, GameObject> symbolToPrefabMap;
// Suppose each symbol type has an associated prefab GameObject that's set in the Unity Inspector
public GameObject nyarlathotepPrefab;
public GameObject azathothPrefab;
public GameObject cthulhuPrefab;
// ... (Other prefabs)
private void Awake()
{
symbolToPrefabMap = new Dictionary<EldritchSymbols, GameObject>
{
{ EldritchSymbols.Nyarlathotep, nyarlathotepPrefab },
{ EldritchSymbols.Azathoth, azathothPrefab },
{ EldritchSymbols.Cthulhu, cthulhuPrefab },
// ... (Rest of the prefab mappings)
};
}
This new dictionary, symbolToPrefabMap, directly maps symbol types to their prefab objects. You would then use this dictionary in a GetPrefabFromSymbolType method as previously described or directly within your instantiation logic.
Here's how you can use the symbolToPrefabMap to instantiate prefabs during the loading process:
csharp
public void LoadData(GameData data)
{
// ... (other load logic)
for (int i = 0; i < data.symbolSlotsState.Count; ++i)
{
EldritchSymbols? symbolType = data.symbolSlotsState[i];
if (symbolType.HasValue)
{
if (symbolToPrefabMap.TryGetValue(symbolType.Value, out GameObject prefab))
{
Instantiate(prefab, symbolSlots[i].position, Quaternion.identity, symbolSlots[i]);
}
else
{
Debug.LogError("Prefab not found for symbol type: " + symbolType.Value);
}
}
}
// ... (other load states)
}
Ensure your prefabs are correctly assigned in the script or loaded appropriately in the Awake or Start method before attempting to instantiate them during the load process.
User
I do have a mapping for the object to spawn, its called eldritchSymbolPrefabs
Assistant
Since you have an array eldritchSymbolPrefabs that contains the prefabs corresponding to the different EldritchSymbols, you can use the index of each symbol in the EldritchSymbols enum to reference the correct prefab when instantiating during the load process.
To facilitate this, you'll need to ensure your eldritchSymbolPrefabs array is in the same order as the EldritchSymbols enum. Then, you can use the enum's integer value to get the correct prefab for instantiation:
csharp
public GameObject[] eldritchSymbolPrefabs; // Make sure this is populated in the inspector in the exact order of the EldritchSymbols enum
public void LoadData(GameData data)
{
// ... (other load logic)
for (int i = 0; i < data.symbolSlotsState.Count; ++i)
{
EldritchSymbols? symbolType = data.symbolSlotsState[i];
if (symbolType.HasValue)
{
// Convert the enum to its corresponding integer index
int prefabIndex = (int)symbolType.Value;
// Make sure the index is within the bounds of the array
if (prefabIndex >= 0 && prefabIndex < eldritchSymbolPrefabs.Length)
{
GameObject symbolPrefab = eldritchSymbolPrefabs[prefabIndex];
Instantiate(symbolPrefab, symbolSlots[i].position, Quaternion.identity, symbolSlots[i]);
}
else
{
Debug.LogError("Invalid prefab index for symbol type: " + symbolType.Value);
}
}
}
// ... (other load states)
}
This code assumes that symbolSlotsState in GameData correctly represents the symbol placed in each slot by its enum type, and null if the slot is empty. Also, it is very important to have the eldritchSymbolPrefabs array elements ordered in the exact same sequence as the EldritchSymbols enum values for this method to work correctly:
csharp
public enum EldritchSymbols
{
Nyarlathotep, // Corresponds to eldritchSymbolPrefabs[0]
Azathoth, // Corresponds to eldritchSymbolPrefabs[1]
Cthulhu, // Corresponds to eldritchSymbolPrefabs[2]
ShubNiggurath, // Corresponds to eldritchSymbolPrefabs[3]
YogSothoth // Corresponds to eldritchSymbolPrefabs[4]
}
Make sure to populate eldritchSymbolPrefabs in Unity's Inspector window with the prefabs in the correct order matching your EldritchSymbols enum. Your save method should also correctly record into GameData which EldritchSymbols is placed into which slot, and the load method should use that information to reconstruct the scene.
User
data.symbolSlotsState[i] = null; // Slot is empty
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.Collections.Generic.List`1[T].set_Item (System.Int32 index, T value) (at <17d9ce77f27a4bd2afb5ba32c9bea976>:0)
LovecraftianPuzzle.SaveData (GameData data) (at Assets/MyPuzzle/LovecraftianPuzzle.cs:383)
Assistant
The ArgumentOutOfRangeException you're encountering suggests that you're trying to access an index in symbolSlotsState that is outside the bounds of the list.
This kind of error usually occurs when you attempt to set an item at an index that doesn't exist in the list (i.e., the list has not been initialized to the required size).
A common approach to prevent this is to ensure that the symbolSlotsState list is initialized with a size that matches your symbolSlots array. Here's how you could initialize the symbolSlotsState list with null for each slot when you start a new game or in the constructor of your GameData class:
csharp
public GameData()
{
symbolSlotsState = new List<EldritchSymbols?>(new EldritchSymbols?[symbolSlots.Length]);
// Initialize other fields...
}
When saving the game state, you should first check if the symbolSlotsState list is large enough to accommodate the data you're trying to store within it. If it's not, you should adjust the size accordingly:
csharp
public void SaveData(GameData data)
{
// Ensure that the list is initialized and the correct size
if (data.symbolSlotsState == null || data.symbolSlotsState.Count != symbolSlots.Length)
{
data.symbolSlotsState = new List<EldritchSymbols?>(new EldritchSymbols?[symbolSlots.Length]);
}
// Now you can safely assign the states based on the symbolSlots
for (int i = 0; i < symbolSlots.Length; ++i)
{
if (symbolSlots[i].childCount > 0)
{
EldritchSymbol symbol = symbolSlots[i].GetChild(0).GetComponent<EldritchSymbol>();
data.symbolSlotsState[i] = symbol.symbolType;
}
else
{
data.symbolSlotsState[i] = null; // Slot is empty
}
}
// ... (save other game states to data)
}
User
In GameData, the symbolSlots does not exist in the current context.
public GameData()
{
symbolSlotsState = new List<EldritchSymbols?>(new EldritchSymbols?[symbolSlots.Length]);
code
// Initialize other fields…
}
Assistant
My apologies for the confusion. Since symbolSlots is a field likely defined in your LovecraftianPuzzle class and not in the GameData class, you can't reference it directly from the GameData constructor.
To initialize symbolSlotsState with the correct number of entries, you need to pass the number of slots as an argument to the GameData constructor from the context where symbolSlots is defined.
Here's how you can modify the GameData class and its constructor to properly initialize the symbolSlotsState list using a passed-in size parameter:
csharp
[System.Serializable]
public class GameData
{
// ... (other fields)
public List<EldritchSymbols?> symbolSlotsState;
public GameData(int numberOfSlots)
{
symbolSlotsState = new List<EldritchSymbols?>(new EldritchSymbols?[numberOfSlots]);
// Initialize other fields...
}
// Add a zero-parameter constructor if needed for other cases
public GameData()
{
// Default initialization
}
// ... (rest of GameData class)
}
And in the LovecraftianPuzzle class or wherever GameData is instantiated and symbolSlots is known, you'd pass the length of the symbolSlots array to the constructor:
csharp
public class LovecraftianPuzzle : MonoBehaviour
{
public Transform[] symbolSlots;
// When creating a new GameData instance
void CreateGameData()
{
GameData data = new GameData(symbolSlots.Length);
// ... use 'data' as needed ...
}
// ... (rest of LovecraftianPuzzle class)
}
Calling new GameData(symbolSlots.Length) from the context where symbolSlots is available allows you to initialize the symbolSlotsState list inside GameData with the correct number of null values (one for each slot). You'll need to adjust the actual places where you create instances of GameData to use the new constructor and to pass the correct length.
User
theres no other way?
Assistant
Certainly, there are alternative approaches you can take. One common strategy is to initialize the symbolSlotsState to a predefined size or dynamically calculate the size where it's being used, without relying on an external variable like symbolSlots. Here is a revised approach:
Initializing symbolSlotsState with a Predefined Size
Assuming you have a fixed number of slots for your symbols, you can define a constant that represents this count and use it to initialize the symbolSlotsState list:
csharp
[System.Serializable]
public class GameData
{
public const int NumberOfSlots = 5; // Assuming you have exactly 5 slots.
public List<EldritchSymbols?> symbolSlotsState;
public GameData()
{
symbolSlotsState = new List<EldritchSymbols?>(new EldritchSymbols?[NumberOfSlots]);
// Initialize other fields...
}
}
This approach is simple but it relies on the assumption that the number of slots will not change dynamically.
Dynamically Calculating the Number of Slots On Save
An alternative is to dynamically allocate the size of symbolSlotsState based on the number of slots at the moment you save your data. To do this, pass the size to the GameData class when saving:
csharp
public class LovecraftianPuzzle : MonoBehaviour
{
// ... Existing members ...
public void SaveGame()
{
GameData data = new GameData();
SaveData(data);
// Now serialize 'data' to a file or PlayerPrefs.
}
public void SaveData(GameData data)
{
// Ensure we initialize the list with the size of symbolSlots array.
data.symbolSlotsState = new List<EldritchSymbols?>(new EldritchSymbols?[symbolSlots.Length]);
for (int i = 0; i < symbolSlots.Length; ++i)
{
if (symbolSlots[i].childCount > 0)
{
EldritchSymbol symbol = symbolSlots[i].GetChild(0).GetComponent<EldritchSymbol>();
data.symbolSlotsState[i] = symbol.symbolType;
}
else
{
data.symbolSlotsState[i] = null; // Slot is empty.
}
}
}
}
User
Loaded symbol slots state is invalid or incorrectly sized.
0x00007ff7ef3e692d (Unity) StackWalker::GetCurrentCallstack
0x00007ff7ef3eb9f9 (Unity) StackWalker::ShowCallstack
0x00007ff7f03bce71 (Unity) GetStacktrace
0x00007ff7f0a7671e (Unity) DebugStringToFile
Assistant
The error message you're seeing suggests that there is a mismatch between the expected size of the symbolSlotsState list and its actual size when you try to process it during loading. There are a few things you can check to troubleshoot this issue:
Ensuring List Initialization
Ensure that when you create a new GameData instance, the list is initialized properly with the expected number of slots:
csharp
[System.Serializable]
public class GameData
{
public List<EldritchSymbols?> symbolSlotsState;
public GameData(int numberOfSlots)
{
symbolSlotsState = new List<EldritchSymbols?>(new EldritchSymbols?[numberOfSlots]);
// ... initialize other fields
}
// Make sure you have a parameterless constructor if needed
// for other paths that may serialize/deserialize this class.
public GameData()
{
// Default initialization
}
}
Make sure there is no path where GameData is created without setting up symbolSlotsState properly.
Checking Load Logic
When you load the game, verify that you properly deserialize GameData and that symbolSlotsState is actually populated with the correct number of slots.
csharp
public void LoadData(GameData data)
{
if (data.symbolSlotsState == null || data.symbolSlotsState.Count != symbolSlots.Length)
{
Debug.LogError("Loaded symbol slots state is invalid or incorrectly sized.");
return;
}
// ... (rest of your loading logic)
}
This logic implies that symbolSlots must be initialized before you try to load symbolSlotsState. If symbolSlots has not been initialized by this point, its Length will be 0, which can trigger the error.
Safe Deserialization
If the list size can vary, consider using a more flexible approach when deserializing to avoid indexing issues:
[System.Serializable]
public class Glyphs
{
public EldritchSymbols symbolType;
public GameObject symbolGlyph;
public bool isActive;
}
[System.Serializable]
public class Book
{
public string title;
public EldritchSymbols symbolType;
public GameObject symbolPrefab;
}
/*[System.Serializable]
class PuzzleData
{
public List<Glyphs> glyphs;
public List<Book> books;
public List<EldritchSymbols> correctOrder;
public List<EldritchSymbols> currentOrder;
public Dictionary<EldritchSymbols, int> symbolToSlotIndex;
}*/
public void PlaceSymbol(EldritchSymbols symbol)
{
int bookIndex = books.FindIndex(b => b.symbolType == symbol);
Book book = books.Find(b => b.symbolType == symbol);
string title = book?.title;
// Check if the book index is valid and the corresponding slot is empty
if (bookIndex >= 0 && bookIndex < books.Count && symbolSlots[bookIndex].childCount == 0)
{
bool itemFound = false; // Flag variable to check if the item was found in the inventory
for (int t = 0; t < InvManager.MaxItems; t++) //Starting a loop in the slots of the inventory:
{
if (InvManager.Slots[t].IsTaken == true) //Checking if there's an item in this slot.
{
Item ItemScript = InvManager.Slots[t].Item.GetComponent<Item>(); //Getting the item script from the items inside the bag.
if (ItemScript.Name == title)
{
itemFound = true; // Set the flag to true
ItemScript.ItemDropType = Item.ItemDropTypes.Destroy;
InvManager.RemoveItem(ItemScript.gameObject.transform, 1);
break; // Break out of the loop since the item was found
}
}
}
if (itemFound) // Check if the item was found in the inventory
{
GameObject symbolObject = Instantiate(
books[bookIndex].symbolPrefab,
symbolSlots[bookIndex].position,
Quaternion.Euler(0, 24, -90), // Rotate 90 degrees around the Z axis
symbolSlots[bookIndex]);
Item itemScript = symbolObject.GetComponent<Item>();
itemScript.name = itemScript.Name;
if (!currentOrder.Contains(symbol)) // Check if the symbol is already in the list
{
currentOrder.Add(symbol); // Add it only if it's not present
// Check if the newly placed symbol is in the correct position
if (currentOrder.Count <= correctOrder.Count && currentOrder[currentOrder.Count - 1] == correctOrder[currentOrder.Count - 1])
{
// Find the Glyph that has the same symbol
Glyphs glyph = glyphs.Find(g => g.symbolType == symbol);
if (glyph != null)
{
// Define the emissive color
Color emissiveColor = Color.red; // replace with the desired color
glyph.isActive = true;
// Get all children of the Glyph
foreach (Transform child in glyph.symbolGlyph.transform)
{
// Get the SpriteRenderer of the child
SpriteRenderer spriteRenderer = child.GetComponent<SpriteRenderer>();
if (spriteRenderer != null)
{
// Apply the emissive color to the SpriteRenderer
spriteRenderer.material.SetColor("_EmissionColor", emissiveColor);
}
}
}
}
}
playerAudioSource.PlayOneShot(placeSymbolSound);
}
else
{
NotificationUI notificationUI = FindObjectOfType(typeof(NotificationUI)) as NotificationUI;
notificationUI.SendMsg("<color=white>The book " + "<color=red>" + books[bookIndex].title + "</color> is missing");
}
}
NarrativeUI narrative = FindObjectOfType(typeof(NarrativeUI)) as NarrativeUI;
narrative.SendMsg("Symbol of " + books[bookIndex].symbolType, 4);
StartCoroutine(player.GetComponent<PlayerInteraction>().InteractionDelay());
CheckPuzzleSolved();
}
private void CheckPuzzleSolved()
{
if (currentOrder.Count == correctOrder.Count)
{
bool isSolved = true;
for (int i = 0; i < correctOrder.Count; i++)
{
if (currentOrder[i] != correctOrder[i])
{
isSolved = false;
break;
}
}
if (isSolved)
{
questSystem._quest3 = true;
StartCoroutine(GatewayAnimation());
}
}
}
public IEnumerator GatewayAnimation()
{
portalAnimator.SetBool("OpenGateway", true);
MeshCollider gatewayMeshFilter = portalAnimator.gameObject.GetComponent<MeshCollider>();
gatewayAudio.Play();
puzzleAudio.PlayOneShot(puzzleSolvedSound);
gatewayMeshFilter.enabled = false;
yield return new WaitForSeconds(1f);
portalAnimator.SetBool("OpenGateway", false);
foreach (Transform slot in symbolSlots)
{
if (slot.childCount > 0)
{
Vector3 effectPosition = slot.position; // Modify as needed to align with the symbol
Instantiate(bookParticlePrefab, effectPosition, Quaternion.identity, slot);
GameObject shadowPeople = Instantiate(shadowPeoplePrefab, effectPosition, Quaternion.identity, slot);
shadowPeople.GetComponent<AudioSource>().enabled = false;
shadowPeople.name = shadowPeoplePrefab.name;
fearSystem.currentFear += 100;
Destroy(slot.GetChild(1).gameObject, 5);
//Stop puzzle from working at all
}
}
}
public void ResetPuzzle()
{
currentOrder.Clear();
foreach (Transform slot in symbolSlots)
{
if (slot.childCount > 0)
{
Destroy(slot.GetChild(0).gameObject);
}
}
}
public void RemoveSymbol(EldritchSymbols symbol)
{
// Find the index of the symbol in the currentOrder list
int index = currentOrder.FindIndex(s => s == symbol);
int bookIndex = books.FindIndex(b => b.symbolType == symbol);
Book book = books.Find(b => b.symbolType == symbol);
string title = book?.title;
// Check that the index is valid
if (index >= 0 && index < currentOrder.Count)
{
// Find the corresponding symbol in the symbolSlots array
for (int i = 0; i < symbolSlots.Length; i++)
{
if (symbolSlots[i].childCount > 0)
{
GameObject symbolObject = symbolSlots[i].GetChild(0).gameObject;
EldritchSymbols symbolInSlot = symbolObject.GetComponent<EldritchSymbol>().symbolType;
if (symbolInSlot == symbol)
{
// Find the Glyph that has the same symbol
Glyphs glyph = glyphs.Find(g => g.symbolType == symbol);
if (glyph != null)
{
// Define the emissive color
Color emissiveColor = Color.green; // replace with the desired color
glyph.isActive = false;
// Get all children of the Glyph
foreach (Transform child in glyph.symbolGlyph.transform)
{
// Get the SpriteRenderer of the child
SpriteRenderer spriteRenderer = child.GetComponent<SpriteRenderer>();
if (spriteRenderer != null)
{
// Apply the emissive color to the SpriteRenderer
spriteRenderer.material.SetColor("_EmissionColor", emissiveColor);
}
}
}
// Remove the symbol from currentOrder and destroy the symbol object
currentOrder.RemoveAt(index);
playerAudioSource.PlayOneShot(placeSymbolSound);
// Instantiate a new instance of the book prefab and add it to inventory
GameObject bookPrefab = books.Find(b => b.symbolType == symbol).symbolPrefab;
// Instantiate an item from the Item prefab
GameObject bookInstantiate = Instantiate(bookPrefab);
Item bookItemScript = bookInstantiate.GetComponent<Item>();
EldritchSymbols bookSymbol = bookInstantiate.GetComponent<EldritchSymbol>().symbolType;
bookItemScript.name = bookItemScript.Name;
bookSymbol = symbolInSlot;
InvManager.AddItem(bookInstantiate.transform);
//InvManager.AddItem("AddItem(Transform item). How To Add The Book That Match The Symbol In Inventory?");
Destroy(symbolObject);
StartCoroutine(player.GetComponent<PlayerInteraction>().InteractionDelay());
break;
}
}
}
}
}
public void LoadData(GameData data)
{
currentOrder = data.currentOrder;
//glyphs = data.glyphs;
// Load glyphs state
foreach (var glyphData in data.glyphsState)
{
// Find the corresponding Glyph object in your scene or list
var glyph = glyphs.Find(g => g.symbolType == glyphData.Key);
if (glyph != null)
{
glyph.isActive = glyphData.Value;
// Update the visual state of the glyph based on the loaded isActive value
//UpdateGlyphDisplay(glyph.symbolGlyph, glyph.isActive);
}
}
}
public void SaveData(GameData data)
{
//data.glyphs = this.glyphs;
data.currentOrder = this.currentOrder;
foreach (Glyphs glyph in glyphs)
{
// This check prevents trying to add the same key more than once.
if (!data.glyphsState.ContainsKey(glyph.symbolType))
{
data.glyphsState.Add(glyph.symbolType, glyph.isActive);
}
else
{
// If the key already exists, you can choose to update its value or throw an exception/warning.
data.glyphsState[glyph.symbolType] = glyph.isActive;
}
}
}
// Method used to update the visual display of a glyph based on isActive
private void UpdateGlyphDisplay(GameObject glyphObject, bool isActive)
{
// Set the visibility, color, or any other display-relevant attribute of the glyph
// Example: setting the glyph’s GameObject to active or not
glyphObject.SetActive(isActive);
// If the glyphs have other visual representations you need to update,
// add that logic here.
}
LoadData
Ensure Consistency Across Sessions: Ensure that any logic that modifies the glyph state during gameplay is also properly considering the saved state and not just resetting to default values when the game reloads or restarts.
By carefully debugging step by step and confirming that each part of the save/load cycle works as expected, you should be able to identify and fix the issue with the active state of glyphs not being loaded correctly.
Save the State: Make sure your SaveData function correctly saves the isActive state of the glyphs so it can be loaded later.
csharp
public void SaveData(GameData data)
{
foreach (Glyphs glyph in glyphs)
{
if (!data.glyphsState.ContainsKey(glyph.symbolType))
{
data.glyphsState.Add(glyph.symbolType, glyph.isActive);
}
else
{
data.glyphsState[glyph.symbolType] = glyph.isActive;
}
}
// ... (other saving logic)
}
By encapsulating the visual update in its own function, you maintain better control over the visual state and ensure consistency across save/load operations and gameplay events.
Remember to update the glyph's emission property properly. Depending on whether you're using the Built-in Render Pipeline, URP (Universal Render Pipeline), or HDRP (High-Definition Render Pipeline), you might have to modify material properties slightly differently. Always ensure that the material's emission is enabled before changing its color.
public void LoadData(GameData data)
{
// ... (existing load logic)
foreach (var savedSymbol in data.savedSymbols)
{
GameObject prefab = GetPrefabFromSymbolType(savedSymbol.type); // Implement this method to map types to prefabs
if (prefab != null)
{
GameObject symbolObject = Instantiate(prefab, savedSymbol.position, savedSymbol.rotation);
// ... (Set parent or other properties as necessary)
}
}
// ... (rest of the load logic)
}
Considerations:
Ensure you are saving and loading at the correct times in your game's lifecycle.
When you load the game, clear any existing symbols in the scene before instantiating the saved symbols to avoid duplicates.
You might need to handle references to parent objects or other properties specific to your game.
Make sure to remove a SavedSymbol from GameData.savedSymbols if the corresponding symbol is destroyed or its state changes during gameplay.
For more complex objects with scripts or dynamic components, you might need to store additional data to recreate their state correctly.
Serialization of certain types like Quaternion and Vector3 is supported by Unity, but be mindful of references to other GameObjects or components that may not be serializable directly.
Remember, the actual implementation details may vary based on how your game and objects are structured. The information here serves as a guideline, and you'll need to adapt it to fit your specific situation.
During Gameplay
Every time a symbol is correctly placed in a symbolSlot during gameplay, save its state.
Example of persisting state while placing a symbol:
csharp
public void PlaceSymbol(EldritchSymbols symbol)
{
// Your existing logic to place a symbol...
// ...
// Add the symbol's state to your saved data immediately after placing it
if (DataPersistenceManager.Instance.HasGameData())
{
GameData data = DataPersistenceManager.Instance.LoadGame();
SavedSymbol savedSymbol = new SavedSymbol
{
type = symbol,
// ... other necessary data such as the slot index, position, rotation, etc.
};
data.savedSymbols.Add(savedSymbol);
DataPersistenceManager.Instance.SaveGame(data); // Persist the updated game data
}
}
This approach relies on your persistence system having a reference to the DataPersistenceManager instance and being able to save and load data at appropriate times.
Please tailor the actual implementation to fit with your game's structure and the details of your data persistence manager. The key concepts are to check for existing game data upon loading and then to use that data to re-create the state of the game as closely as possible to how it was when the game was last saved.
public void LoadData(GameData data)
{
// ... (other load logic)
for (int i = 0; i < data.symbolSlotsState.Count; ++i)
{
EldritchSymbols? symbolType = data.symbolSlotsState[i];
if (symbolType.HasValue)
{
// Use the symbol type to get the correct prefab
GameObject symbolPrefab = GetPrefabFromSymbolType(symbolType.Value);
Instantiate(symbolPrefab, symbolSlots[i].position, Quaternion.identity, symbolSlots[i]);
}
}
// ... (other load states)
}
Integration
Since you're using the currentOrder list to maintain the state of the puzzle, you need to ensure that both saving and loading mechanisms work with the currentOrder list appropriately. On save, note down the currentOrder. On load, reconstruct currentOrder and the state of the slots based on the loaded symbolSlotsState.
Remember to recreate any other state data (e.g., which slots have which symbols, which symbols are active/inactive, etc.) during both save and load processes to ensure all necessary game state information is captured and correctly restored.
Combining the strategies above with your existing data structures should enable you to recreate the state of your puzzle during the loading process. Ensure that instantiation only occurs after all necessary cleanup to avoid duplications or incorrect game states.
When you load the game data, you'll want to make sure that you check the size of the symbolSlotsState list to be certain that it matches what you're expecting:
csharp
public void LoadData(GameData data)
{
// Check if the load list is valid
if (data.symbolSlotsState == null || data.symbolSlotsState.Count != symbolSlots.Length)
{
Debug.LogError("Loaded symbol slots state is invalid or incorrectly sized.");
return;
}
// Continue with load logic...
// ...
}
Make sure you also handle adding and removing from symbolSlotsState appropriately when symbols are placed into or removed from slots during the game. Please adjust your initialization, save, and load logic using these guidelines to prevent the ArgumentOutOfRangeException.
This way, you allocate the correct amount of space as you save, based on the actual number of symbol slots at that time.
Take note: In both strategies, when you load and deserialize GameData, ensure that the code which processes symbolSlotsState accounts for the actual size of the list. The strategies outlined offer ways to deal with the problem either by fixing the size according to the game design or by adjusting the size dynamically during runtime as needed.
csharp
public void LoadData(GameData data)
{
if (data.symbolSlotsState == null)
{
Debug.LogError("Loaded symbol slots state is null.");
return;
}
for (int i = 0; i < data.symbolSlotsState.Count; ++i)
{
EldritchSymbols? symbolType = data.symbolSlotsState[i];
if (symbolType.HasValue)
{
// Instantiate symbols for the slots that were saved with a symbol
}
}
}
In this approach, you rely on the deserialized symbolSlotsState list's own count rather than an external array's length, thus avoiding possible ArgumentOutOfRangeException issues.
Saving with Consistent Size
Ensure that your saving logic matches the number of slots that symbolSlotsState is expected to have:
csharp
public void SaveData(GameData data)
{
int slotCount = symbolSlots.Length; // Make sure this matches the initialization logic in GameData.
data.symbolSlotsState = new List<EldritchSymbols?>(new EldritchSymbols?[slotCount]);
for (int i = 0; i < slotCount; ++i)
{
// ... save the state of each slot as previously described ...
}
}
Double-check all the points where GameData is being instantiated and used to ensure that you are correctly initializing, serializing, and deserializing the symbolSlotsState list with the correct number of entries. If these checks don't resolve the issue, you may need to examine your serialization and deserialization processes to ensure they're correctly handling the list and preserving its size.