visual studio – TCP/IP in Unity


I am trying to operate switch from a python script outside Unity. It is basically a sphere thrown at a wall; when I use keyboard, the game is working fine; as soon as I use TCP/IP I see Debug print statements in the console, but not the ball appearing in the game. What can be causing this?
Code:

using UnityEngine;

public class SphereThrower : MonoBehaviour
{
    public GameObject leftSpherePrefab;
    public GameObject rightSpherePrefab;
    public Transform leftWall;
    public Transform rightWall;

    private GameObject currentBall;

    private Vector3 leftSphereInitialPosition;
    private Vector3 rightSphereInitialPosition;

    void Start()
    {
        if (leftSpherePrefab != null && rightSpherePrefab != null)
        {
            leftSphereInitialPosition = leftSpherePrefab.transform.position;
            rightSphereInitialPosition = rightSpherePrefab.transform.position;
            

            leftSpherePrefab.SetActive(false);
            rightSpherePrefab.SetActive(false);
        }
        else
        {
            Debug.LogError("Left or right sphere prefab is not assigned!");
        }
    }

    public void HandleTrigger(string trigger)
    {
        switch (trigger)
        {
            case "0":
                Debug.Log("Trigger 0: Throwing left sphere.");
                ThrowSphere(leftSpherePrefab, leftSphereInitialPosition);
                break;
            case "1":
                Debug.Log("Trigger 1: Throwing right sphere.");
                ThrowSphere(rightSpherePrefab, rightSphereInitialPosition);
                break;
            case "L":
                Debug.Log("Trigger L: Moving ball to left wall.");
                MoveBallToWall(currentBall, leftWall.position);
                break;
            case "R":
                Debug.Log("Trigger R: Moving ball to right wall.");
                MoveBallToWall(currentBall, rightWall.position);
                break;
            default:
                Debug.Log("Invalid trigger received: " + trigger);
                break;
        }
    }

    void ThrowSphere(GameObject spherePrefab, Vector3 initialPosition)
    {
        if (currentBall != null)
        {
            Destroy(currentBall);
        }

        currentBall = Instantiate(spherePrefab, initialPosition, Quaternion.identity);
        currentBall.SetActive(true);
    }

    void MoveBallToWall(GameObject ball, Vector3 wallPosition)
    {
        Vector3 direction = wallPosition - ball.transform.position;
        direction.Normalize();

        Rigidbody rb = ball.GetComponent<Rigidbody>();
        if (rb != null)
        {
            rb.velocity = Vector3.up * 5f;
            rb.useGravity = true;
        }

        if (rb != null)
        {
            rb.velocity += direction * 5f;
            Destroy(ball, 6f);

            Debug.Log("Distance to left wall: " + Vector3.Distance(ball.transform.position, leftWall.position));
            Debug.Log("Distance to right wall: " + Vector3.Distance(ball.transform.position, rightWall.position));
        }
    }
}
**TCP/IP Code:**
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;


public class communication : MonoBehaviour
{
   public SphereThrower sphereThrower; // Reference to the SphereThrower component


   private TcpListener server;
   private int port = 5680; // Choose a port for your TCP server


   void Start()
   {
       // Start TCP server
       server = new TcpListener(IPAddress.Loopback, port);
       server.Start();
      
       // Begin accepting clients asynchronously
       Task.Run(() => AcceptClients());
   }


   async Task AcceptClients()
   {
       while (true)
       {
           TcpClient client = await server.AcceptTcpClientAsync();


           // Handle client messages
           Task.Run(() => HandleClient(client));
       }
   }


   void HandleClient(TcpClient client)
   {
       NetworkStream stream = client.GetStream();
       byte[] buffer = new byte[1024];


       while (true)
       {
           int bytesRead = stream.Read(buffer, 0, buffer.Length);
           string message = Encoding.ASCII.GetString(buffer, 0, bytesRead).TrimEnd('\0');


           // Debug log to check if the message is received correctly
           Debug.Log("Received message: " + message);


           // Call HandleTrigger method of SphereThrower
           sphereThrower.HandleTrigger(message);


           // Check if the loop is terminating properly
           //if (bytesRead == 0)
           //{
             //  Debug.Log("No more bytes to read, terminating loop.");
               //break;
           //}
           //else
           //{
             //  Debug.Log("Bytes read: " + bytesRead);
           //}
       }
   }
}



I am expecting sphere to appear accordingly when I press 0/1 in different software

Leave a Reply

Your email address will not be published. Required fields are marked *