I want to using networking to activate a button on my client from my server upon receiving a certain message ("GO_TO_SCENE_3"
). My client receives a byte[]
message, but the button remains disabled, I want it to enable when the button is pressed on the server.
using System.Net.Sockets;
using System.Text;
using System;
using Unity Engine;
using Unity Engine.UI; // For handling UI buttons
using Unity Engine.SceneManagement; // For scene transition
public class Client : MonoBehaviour
{
private TcpClient client;
private NetworkStream stream;
private bool isReadyForSceneChange = false;
public Button goToSceneButton; // Reference to the button in the Unity editor
void Start()
{
// Initially hide the button
goToSceneButton.gameObject.SetActive(false);
// Connect to the server
client = new TcpClient("127.0.0.1", 8888); // Use server's IP and port
stream = client.GetStream();
Debug.Log("Connected to server.");
ListenForServerMessages();
}
// Wait for the server to send the message
void ListenForServerMessages()
{
byte[] buffer = new byte[1024];
stream.BeginRead(buffer, 0, buffer.Length, OnMessageReceived, buffer);
}
void OnMessageReceived(IAsyncResult result)
{
byte[] buffer = (byte[])result.AsyncState;
int bytesRead = stream.EndRead(result);
string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Debug.Log("Message from server: " + message);
if (message == "GO_TO_SCENE_3")
{
isReadyForSceneChange = true;
// Show the "Go to Scene 3" button
goToSceneButton.gameObject.SetActive(true);
}
// Continue listening for any further messages
ListenForServerMessages();
}
// This method is linked to the "Go to Scene 3" button's On Click event in Unity
public void GoToScene3()
{
// Transition to the next scene (Scene 3)
SceneManager.LoadScene("Scene3");
}
private void On Application Quit()
{
if (stream != null) stream.Close();
if (client != null) client.Close();
}
}
When I press the “hello” button on server, my client’s button should be enabled. This button will change the active scene from scene2 to scene3 when pressed.
Why isn’t the button on the client getting enabled?
1