J.Titor.0
J.Titor.0

Reputation: 79

Can Unity Editor enter PlayMode without reloading a script

I am writing an Unity editor script that creates TCP server accepts requests from other application, but I found out that "clicking" play mode reloads my editor scripts which will interrupts the connection by re-initializing my server. Is there any way Unity Editor can stop reloading this particular script and makes it up running at all time?

    [InitializeOnLoadMethod]
    static void InitializeOnLoadMethod()
    {
        if (m_Server == null)
        {
            EditorApplication.update += Update;
            Debug.Log("starting");
            IPAddress ip = IPAddress.Parse(ipAdress);
            m_Server = new TcpListener(ip, port);
            m_Server.Start();
            Debug.Log("Sever started");
            Debug.Log(ip);
            Debug.Log(port);


            //Wait for async client connection 
            m_Server.BeginAcceptTcpClient(ClientConnected, null);
            OnServerStarted?.Invoke();
        }

In other words, is there a way to keep all my static variables and my editor coroutines after PlayMode is invoked? I did some search and I think domain reloading has caused it

Upvotes: 2

Views: 1942

Answers (1)

MikeB
MikeB

Reputation: 45

Haven't tried this and don't have Unity on this PC to test, but can you gate it by using the isPlaying check:

if (!Application.isPlaying)
{
    // Do your server stuff here
}

https://docs.unity3d.com/ScriptReference/Application-isPlaying.html

In other words, don't run the code while the game is playing, which is true when you hit the Play button?

Upvotes: 0

Related Questions