Forum begins after the advertisement:

 


[Part 22] NullReferenceException

Home Forums Video Game Tutorial Series Creating a Farming RPG in Unity [Part 22] NullReferenceException

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #17902
    Sidinei Rocha Vianna
    Level 1
    Participant
    Helpful?
    Up
    0
    ::

    When I go to sleep and the game tries to save, this error appears.

    NullReferenceException: Object reference not set to an instance of an object FarmSaveState.Export () (at Assets/Scripts/Save/FarmSaveState.cs:26) GameStateManager.ExportSaveState () (at Assets/Scripts/GameStateManager.cs:163) GameStateManager+<TransitionTime>d__12.MoveNext () (at Assets/Scripts/GameStateManager.cs:148) UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <88d854ea2c91426ebc464f01cd71aa85>:0)

    #17903
    Tarha Apustaja
    Level 4
    AI Assistant
    (BETA)
    Helpful?
    Up
    0
    ::

    Based on the reference information, this looks like the scenario described in the Part 25 tutorial where a NullReferenceException can occur when going to sleep immediately after starting the game.

    The solution is to add null checks in the FarmSaveState.Export() method. Specifically, modify the method to ensure that LandManager.farmData and its components are not null before accessing them:

    public static FarmSaveState Export() {
        List landData = new List();
        List cropData = new List();
    
        if (LandManager.farmData != null) {
            landData = LandManager.farmData.Item1;
            cropData = LandManager.farmData.Item2;
        }
    
        List eggsIncubating = new List();
        if(IncubationManager.eggsIncubating != null) {
            eggsIncubating = IncubationManager.eggsIncubating;
        }
    
        return new FarmSaveState(landData, cropData, eggsIncubating);
    }

    This approach ensures that even if farmData is null, the method will still create an empty list and prevent the NullReferenceException.

    #17907
    Jonathan Teo
    Level 18
    Moderator
    Helpful?
    Up
    0
    ::

    Tarha is right here. Try the above fix and let me know how it goes

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.

Go to Login Page →


Advertisement below: