Reputation: 63
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.
Upvotes: 2
Views: 43329
Reputation: 598
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(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.
Upvotes: 3
Reputation:
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);
}
}
Upvotes: 0