1

is there such a way to run a method in all scenes in unity without passing data from one screen to another? What I want to do is assume that I have a method which counts the time like stopwatch. When I open the game it starts counting on main screen like 1,2,3... and when I go another screen it should keep running the method and continue counting 4,5,6... and it should continue like this when I switch to other screens.

I thought that it can be done using a static variable in a script and using the same script in all scenes in a game object. But I wonder if there is an easier approach as I said in above like running one global method in all screens once game is launched.

Serkan Tarakcı
  • 177
  • 2
  • 13
  • You *could* use a `ScriptableObject` for this, though those are typically just used to keep project-wide data rather than code. – 3Dave May 05 '21 at 20:04
  • Theres a bunch of choices. What have you tried – BugFinder May 05 '21 at 20:51
  • https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html Is this help you? – TimChang May 06 '21 at 01:09
  • 1
    you need a preload scene. this is an absolute basic of game engines. it's the single biggest misunderstanding in Unity! https://stackoverflow.com/a/35891919/294884 – Fattie May 06 '21 at 12:40
  • This one could be the approved answer. Thank you. I also thank to the rest who spend their valuable time for me. – Serkan Tarakcı May 06 '21 at 20:14

2 Answers2

1

Here is an example of class, that logs value every second. You can change ShowCurrentValue function to one you need. This will work, regardless of changing scene. You can start and stop it with corresponding fucntions from any place in project.

using UnityEngine;
using System.Threading;

public class Counter
{
    public static ulong CurrentValue { get; set; } = 0;
    private static Thread cThread = null;
    public static void Start()
    {
        if (cThread == null)
            cThread = new Thread(ShowCurrentValue);
        cThread.Start();
    }

    public static void Pause()
    {
        if (cThread != null)
        {
            cThread.Abort();
            CurrentValue++;
        }
        cThread = null;
    }

    private static void ShowCurrentValue()
    {
        while (true)
        {
            Debug.Log(CurrentValue);
            Thread.Sleep(1000);
            CurrentValue++;
        }
    }
}
Observer16
  • 11
  • 1
  • 2
    unfortunately this is of almost no value in Unity, because **it's not a MonoBehavior**. the entire purpose of having a preload scene in Unity is for this issue. https://stackoverflow.com/a/35891919/294884 – Fattie May 06 '21 at 12:42
0

You are looking LoadAdditive I believe. Also check the docs once LoadAdditive

  SceneManager.LoadScene("YourScene", LoadSceneMode.Additive);
Syed Mohib Uddin
  • 718
  • 7
  • 16