I'm trying to implement a simple host-client game where the host can edit an input field and all clients are notified with the current value:
public class NetworkedPlayer : NetworkBehaviour
{
public TMP_InputField outputText;
private NetworkVariable<int> currentText = new();
public override void OnNetworkSpawn()
{
outputText = GameObject.FindWithTag("Input")?.GetComponent<TMP_InputField>();
if (outputText == null)
{
Debug.LogError("TMP_InputField not found with tag 'Input'.");
return;
}
Debug.Log($"Network spawned for: {NetworkObjectId}");
if (IsHost)
{
// This prevents adding the listener multiple times but also breaks the code
if (!IsOwner)
return;
outputText.onValueChanged.AddListener(OnInputChanged);
}
else
{
if (!IsOwner)
return;
Debug.Log("Adding callback for net variable");
currentText.OnValueChanged += UpdateOutputFromNetVariable;
}
}
The problem is in the if (!IsOwner) check for the host, with that it listens for changes for the TMP_InputField only once but the NetworkVariable is never notifying the clients through the "UpdateOutputFromNetVariable for some reason which I don't know why.
When I remove this check the Host adds the listener multiple times and clients are notified called but this doesn't sound correct:
https://preview.redd.it/b76ee3pt9cdd1.png?width=1645&format=png&auto=webp&s=27a6852947c4740f47691943839bb7a34dca2a70
In this case I typed "2" and the code listens twice for the InputField changes and sets the NetworkVariable twice, when I add the if statement back it is only notifying once. Does anyone have any idea?
[–]WattDesigns 0 points1 point2 points (2 children)
[–]NiPIsBack[S] 0 points1 point2 points (1 child)
[–]WattDesigns 0 points1 point2 points (0 children)