# Understanding Background Save & Load

You don't need to do anything extra to save and load data in the background. It will happen as long as `backgroundTask` is set to true. However, you may have to change the way you code a little when working with save files.

## Working With Operations

Normally, if you want something to happen after saving or loading is complete, you would just respect the order of operations and execute your code after the save or load code.

If you've enabled 'Background Task' from the [Save File Setup](/esave/getting-started/components/save-file-setup.md) component or set `backgroundTask` to true through code (which is essentially the same thing), then this rule does not apply.

Instead, you must wait for the saving or loading operation to complete. This can be done easily with the `SaveFileOperation` class in two simple steps.

## Step 1: Getting the Operation

`SaveFile.Load` and `SaveFile.Save` return a SaveFileOperation object. This can be used to determine when saving or loading is completed. Whether it's saving or loading, there is no difference in how you work with the operation object.

{% hint style="warning" %}
It's important for saving to complete before loading, and loading to complete before saving. Which is why there can only be a single operation running at a time for a save file.
{% endhint %}

#### Get Operation From Load

```csharp
SaveFileOperation operation = saveFile.Load();
```

#### Get Operation From Save

```csharp
SaveFileOperation operation = saveFile.Save();
```

#### Get Operation After Calling Save or Load

Save files store the most recent save file operation in memory. If you have recently called `SaveFile.Load` or `SaveFile.Save`, you can use `SaveFile.operation` to get the operation. This will be null if load or save was not called.

```csharp
SaveFileOperation operation = saveFile.operation;
```

## Step 2: Waiting for Completion

There are 2 ways that you can check if the save file operation is complete.

### On Operation Ended Event (RECOMMENDED)

{% hint style="warning" %}
Only use the `onOperationEnded` event for save files that will save & load in the background.
{% endhint %}

`SaveFileOperation.onOperationEnded` will be invoked when the operation has ended (when the operation state is either completed, canceled, or failed). Here's an example of how you can use this to execute some code after loading has completed:

```csharp
private void Start()
{
    // Some code...

    // Get the load operation from a save file
    var operation = saveFile.Load();
    
    // Add on-ended event
    operation.onOperationEnded.AddListener(LoadGame);
}

private void LoadGame()
{
    // Your loading code here...
}
```

If you'd like to ensure the operation was completed successfully, you can use an event like this instead:

```csharp
// Add on-ended event
operation.onOperationEnded.AddListener(() => 
{
    if (operation.state == SaveFileOperation.OperationState.Completed)
    {
        LoadGame();
    }
    else
    {
        // Do something else...
    }
});
```

### Checking the State (NOT RECOMMENDED)

`SaveFileOperation` has an `enum` called `OperationState`. This will be updated as the operation state changes.

There are 5 states:

1. **None**: the operation has not started.
2. **Ongoing**: the operation is currently executing (it's either saving or loading),
3. **Completed**: the operation was successfully completed.
4. **Canceled**: the operation was canceled. This can only be done manually with `SaveFileOperation.Cancel`.
5. **Failed**: an error was encountered during the operation and has been aborted. The error should be displayed in the console.

You can use this to check which state the operation is currently in.

```csharp
if (operation.state == SaveFileOperation.OperationState.Completed)
{
    // Do something...
}
```

If you'd like to do something right after saving or loading is complete, this method **is not recommended** because you will have to use this check every frame.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://espergames.gitbook.io/esave/scripting/understanding-background-save-and-load.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
