How to Use Dontdestroyonload?

So this is probably quite easy but I've never used DontDestroyOnLoad() before and don't know what to do. I have some values in a script I'd like to keep when switching to another screen and I saw that DontDestroyOnLoad() could help me with that but it doesn't seem to work hers my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class data_transfer : MonoBehaviour
{
    DontDestroyOnLoad(transform.gameObject);
}

I get this error message: Assets\scripts\data_transfer.cs(7,43): error CS1001: Identifier expected like I said this is probably relatively easy but I'm new to unity and C# so thank you if you want to help.

1

2 Answers

DontDestroyOnLoad is a method. You simply have to call it inside some other method, like Awake or Start For example like this

public class data_transfer : MonoBehaviour
{
    void Awake()
    {
        DontDestroyOnLoad(transform.gameObject);
    }
}

Awake is called automatically by Unity when GameObject is instantiated, so this will prevent your object from being destroyed when new scene is loaded.

According to Unity's documentation:

Do not destroy the target Object when loading a new Scene. The load of a new Scene destroys all current Scene objects. Call DontDestroyOnLoad to preserve an Object during level loading.

You need to wrap the DontDestroyOnLoad call inside a function or one of the MonoBehaviour's built-in messages callbacks like Awake or Start.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyClass: MonoBehaviour
{
    void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest