I have this code here that it displays a game object when I press E on keyboard the only issue is it works with the host only nothing happens when the client interacts with it when he presses on E. what is the solution or what I'm doing wrong and thx for taking time.
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
public class InteractiveComputer: NetworkBehaviour {
public GameObject computerScreen;
public float interactionRange = 3 f; // Adjust the interaction range as needed
public float displayDuration = 20 f; // Duration to display the computer screen
private bool isComputerScreenVisible = false;
private bool isInteracting = false; // Flag to prevent multiple interactions
private void Start() {
if (IsServer) {
isComputerScreenVisible = false;
computerScreen.SetActive(false);
}
}
bool IsPlayerInRange() {
foreach(var player in NetworkManager.Singleton.ConnectedClientsList) {
if (player != null && Vector3.Distance(transform.position, player.PlayerObject.transform.position) <= interactionRange) {
return true;
}
}
return false;
}
void Update() {
if (!IsServer) return; // Check if the player is nearby
if (IsPlayerInRange()) { // Check if the 'e' key is pressed
if (Input.GetKeyDown(KeyCode.E) && !isInteracting) {
InteractWithComputerServerRpc();
} // Check if the 'A' button on the gamepad is pressed
if (Gamepad.current != null && Gamepad.current.buttonSouth.isPressed && !isInteracting) {
InteractWithComputerServerRpc();
}
}
} [ServerRpc] private void InteractWithComputerServerRpc() {
isComputerScreenVisible = true;
RpcUpdateComputerScreenVisibilityClientRpc(isComputerScreenVisible); // Set a timer to hide the computer screen after the specified duration
Invoke(nameof(HideComputerScreenClientRpc), displayDuration); // Set interacting flag to prevent multiple interactions
isInteracting = true;
} [ClientRpc] private void RpcUpdateComputerScreenVisibilityClientRpc(bool isVisible) {
isComputerScreenVisible = isVisible;
computerScreen.SetActive(isVisible); // If the computer screen is shown on the client, set the interacting flag to true
if (isVisible) {
isInteracting = true;
}
} [ClientRpc] private void HideComputerScreenClientRpc() {
isComputerScreenVisible = false;
computerScreen.SetActive(false); // Reset interacting flag after hiding the computer screen
isInteracting = false;
}
}
JanePosted Feb 13, 2024, 11:41 PM
It seems like the issue you're facing is that the interaction with the computer only works for the host and not for the client. This could be due to the fact that the logic for interaction is currently implemented only on the server-side.
To enable interaction for both the host and the client, you need to ensure that the interaction logic is executed on both sides, server, and client.
Here's how you can modify your code to achieve this:
Regards, Edward manager of tracking system https://www.worktime.com/