"InvalidCastException: Specified cast is not valid."

Hi!
When I enter in Play Mode, it throws an “InvalidCastException: Specified cast is not valid.” at line highlighted in code below:

SaveableEntity.cs

public void RestoreState(object states)
        {
            Dictionary<string, object> stateDictionary = (Dictionary<string, object>)states; // here

            foreach (var state in GetComponents<ISaveable>())
            {
                string typeString = state.GetType().ToString();
                if (stateDictionary.ContainsKey(typeString))
                {
                    state.RestoreState(stateDictionary[typeString]);
                }
            }
        }

The method is called here:

SavingSystem.cs

private void RestoreState(Dictionary<string, object> stateDict)
		{
			foreach (var saveable in FindObjectsByType<SaveableEntity>(FindObjectsSortMode.None))
			{
				string id = saveable.GetUniqueIdentifier();

				if (stateDict.ContainsKey(id))
				{
					saveable.RestoreState(stateDict[id]);
				}
			}
		}

I cannot see why this error happens. Can someone enlighten me?

Actually I didn’t delete the save file, so the save file was incompatible because we changed the data that would be saved.

After “save.sav” was deleted, everything was working fine. :slight_smile:

Yes, unfortunately, that’s one of the downsides of the saving system. If something changes in the data patterns, it invalidates the existing save files due to type casting.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms