using System.Collections;
using System.Collections.Generic;
using TNet;
using UnityEngine;
using UnityTools = TNet.UnityTools;
namespace TNet
{
public class Menu_Autojoin : MonoBehaviour
{
static public Menu_Autojoin instance;
public string serverAddress = "127.0.0.1";
public int serverPort = 5127;
public int channelID = 1;
public bool persistent = false;
public bool allowUDP = true;
public bool connectOnStart = true;
public string disconnectLevel;
void Awake()
{
if (instance == null)
{
instance = this;
TNManager.onConnect += OnConnect;
TNManager.onDisconnect += OnDisconnect;
DontDestroyOnLoad(gameObject);
}
}
void Start() {
if (connectOnStart) Connect();
LoginPro.Manager.ExecuteOnServer("GetUserID", UserIDRetrieval_Success, UserIDRetrieval_Error, null);
}
public void Connect()
{
// We don't want mobile devices to dim their screen and go to sleep while the app is running
Screen.sleepTimeout = SleepTimeout.NeverSleep;
// Connect to the remote server
Debug.Log("Connection starting");
TNManager.Connect(serverAddress, serverPort);
}
void OnConnect(bool result, string message)
{
Debug.Log("We made it!");
if (result)
{
// Make it possible to use UDP using a random port
if (allowUDP) TNManager.StartUDP(Random.Range(10000, 50000));
TNManager.JoinChannel(channelID, null, persistent, 10000, null);
Debug.Log("Successfully connected to server with channel ID " + channelID);
}
else Debug.LogError(message);
}
void OnDisconnect()
{
#if UNITY_4_6 || UNITY_4_7 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2
if (!string.IsNullOrEmpty(disconnectLevel) && Application.loadedLevelName != disconnectLevel)
Application.LoadLevel(disconnectLevel);
#else
if (!string.IsNullOrEmpty(disconnectLevel) &&
UnityEngine.SceneManagement.SceneManager.GetActiveScene().name != disconnectLevel)
UnityEngine.SceneManagement.SceneManager.LoadScene(disconnectLevel);
#endif
}
private void OnDestroy()
{
if (instance == this)
{
TNManager.onConnect -= OnConnect;
TNManager.onDisconnect -= OnDisconnect;
}
TNManager.onConnect -= OnConnect;
TNManager.onDisconnect -= OnDisconnect;
}
//retrieve user ID and set the channel number to this. This is to create user specific rooms on login (empty party channels with only the user)
public void UserIDRetrieval_Success(string[] datas)
{
Debug.Log("User ID Successfully retrieved" + datas[0]);
channelID = int.Parse(datas[0]);
Debug.Log("Channel ID has been converted to int and channel ID has been set: " + channelID);
Debug.Log("sending to connection manager");
}
public void UserIDRetrieval_Error(string errorMessage)
{
Debug.LogError(errorMessage);
}
}
}