Search Unity

I am having difficulty understanding NetworkVariable

Discussion in 'Netcode for GameObjects' started by coolfarmer, Jan 16, 2023.

  1. coolfarmer

    coolfarmer

    Joined:
    Jun 14, 2018
    Posts:
    7
    I am currently experimenting with networking for GameObjects and I am having difficulty understanding how to synchronize the flipX of my 2D character. My character can move, and everything is correctly synchronized, but I want to flip it using the spriteRenderer's FlipX feature.

    Here is the code of PlayerNetwork.cs:

    Code (CSharp):
    1.  
    2. using System.Collections.Generic;
    3. using Unity.Netcode;
    4. using UnityEngine;
    5. using UnityEngine.TextCore.Text;
    6.  
    7. public class PlayerNetwork : NetworkBehaviour
    8. {
    9.     protected Rigidbody2D body;
    10.     protected SpriteRenderer spriteRenderer;
    11.     [SerializeField] protected float speed = 5f;
    12.  
    13.     private NetworkVariable<bool> isFacingRight = new NetworkVariable<bool>(true, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
    14.  
    15.     public override void OnNetworkSpawn()
    16.     {
    17.         body = GetComponent<Rigidbody2D>();
    18.         spriteRenderer = body.GetComponent<SpriteRenderer>();
    19.  
    20.         isFacingRight.OnValueChanged += (bool previousValue, bool newValue) =>
    21.         {
    22.             Debug.Log("ID: " + OwnerClientId + "; isFacingRight: " + isFacingRight.Value);
    23.         };
    24.     }
    25.  
    26.     void Update()
    27.     {
    28.         if (!IsOwner) return;
    29.  
    30.         float horizontalInput = Input.GetAxis("Horizontal");
    31.         Move(new Vector2(horizontalInput * this.speed, 0f));
    32.  
    33.         if (body.velocity.x < 0 && isFacingRight.Value)
    34.         {
    35.             Flip();
    36.         }
    37.         else if (body.velocity.x > 0 && !isFacingRight.Value)
    38.         {
    39.             Flip();
    40.         }
    41.     }
    42.     private void Move(Vector2 newVelocity)
    43.     {
    44.         Vector2 velocity = body.velocity;
    45.         velocity.x = newVelocity.x;
    46.         body.velocity = velocity;
    47.     }
    48.     public void Flip()
    49.     {
    50.         isFacingRight.Value = !isFacingRight.Value;
    51.         spriteRenderer.flipX = !spriteRenderer.flipX;
    52.     }
    53. }
    54.  
    With this code, the character can move and both (host and client) can see it moving. However, when the host presses "A" to move left, the flip is not replicated to the clients, and the same is true for the client to the host. I am confident that I am missing something. The Debug.Log is working correctly on both the client and the host, and I can see both changing the value in isFacingRight.OnValueChanged.

    I think I need help. :(
    Thanks!