- Home /
How to keep Unity Editor TCP client and Tcp Server static variables when entering PlayMode
Hey,
I am trying to build a tcp server on Unity Editor to deal with some request like loading scene and play/stop the game. This server works perfectly in edit mode, but will lose my static variables like Tcp Listerner and Tcp Client when I click Play mode. Is there any way around to avoid this?
Also I use EditorCoroutines to listen for client messge. This coroutine seems to stop as well (of course I lost my static variable client)
The actual code is a bit long, but I can provide a snippets of it.
[ExecuteInEditMode]
//[ExecuteAlways]
public class the_server : MonoBehaviour
{
#region Public Variables
[Header("Network")]
public static string ipAdress = "127.0.0.1";
public static int port = 54010;
public static float waitingMessagesFrequency = 2;
#endregion
#region Private m_Variables
private static TcpListener m_Server = null;
private static TcpClient m_Client = null;
private static NetworkStream m_NetStream = null;
private static byte[] m_Buffer = new byte[49152];
private static int m_BytesReceived = 0;
private static string m_ReceivedMessage = "";
private static IEnumerator m_ListenClientMsgsCoroutine = null;
private static EditorCoroutine m_Ed_ListenClientMsgsCoroutine = null;
#endregion
[InitializeOnLoadMethod]
static void InitializeOnLoadMethod()
{
EditorApplication.update += Update;
if (!EditorApplication.isPlayingOrWillChangePlaymode)
{
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();
}
}
static void Update(){
if (m_Client != null && m_Ed_ListenClientMsgsCoroutine == null)
{
Debug.Log("Found client");
//Start Listening Client Messages coroutine
m_ListenClientMsgsCoroutine = ListenClientMessages();
//EditorCoroutineUtility.StartCoroutine(m_ListenClientMsgsCoroutine, this);
//CallCoroutine(m_ListenClientMsgsCoroutine);
m_Ed_ListenClientMsgsCoroutine = EditorCoroutineUtility.StartCoroutineOwnerless(m_ListenClientMsgsCoroutine);
}
}
}
I think my question is : 1. How to keep my static variables when entering playmode 2. How to keep my thread(coroutine) alive when entering playmode
Thanks for any help in advanced.
PS: I am using Unity 2019.2.14f1 so it doesn't have a setting of Domain Reloading.
Your answer
Follow this Question
Related Questions
Enter play mode from editor script after baking is complete 0 Answers
DestroyImmediate(component.gameObject) destroys component but not gameObject 1 Answer
Add/Remove scene to build settings from editor script and run levels in editor 0 Answers
Keeping state that cannot be serialized between play mode for EditorWindow 1 Answer
Access Monobehavior Instance from Static Function of Editor Script 1 Answer