Hello, I have been trying to make a casual 2 player FPS game using netcode for gameobjects and i have run into a problem. When the host tries to shoot the client, the client looses health, which is an expected outcome, but when the client tries to shoot the host, the host’s health doesnt change and it gives an exception “the client does not have permission to write to network variables”. I tried fixing it by using RPCs but it made more problems that it solved, I also tried searching on youtube but found nothing helpful. Heres the block of code that handles the healt
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
public class HealthScript : NetworkBehaviour
{
NetworkVariable<float> Health = new NetworkVariable<float>();
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
Health.Value = 100;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (IsServer)
{
Debug.Log(Health.Value);
}
}
public void TakeDamage(float damageTaken)
{
Health.Value -= damageTaken;
if (Health.Value <= 0f)
{
Die();
}
}
void Die()
{
Destroy(gameObject);
}
}
and heres the code that handles shooting
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
using Unity.Burst.CompilerServices;
public class gunScript : NetworkBehaviour
{
public float Damage = 27f; // damage of the gun
public float Range = 100f; // range of the gun
public RaycastHit hit;
[SerializeField] Camera mainCamera;
[SerializeField] ParticleSystem muzzleFlash;
// Update is called once per frame
void Update()
{
if (!IsOwner)
{
return;
}
if (Input.GetButtonDown("Fire1"))
{
Shoot(); // shoot
}
}
void Shoot()
{
muzzleFlash.Play();
RaycastHit hit;
if (Physics.Raycast(mainCamera.transform.position, mainCamera.transform.forward, out hit, Range) && IsOwner)
{
Debug.Log(hit.transform.name);
HealthScript takeDamage = hit.transform.GetComponent<HealthScript>();
if (takeDamage != null)
{
takeDamage.TakeDamage(Damage);
}
}
else
{
return;
}
}
}
Im sorry if I made this post inccorecly or made some gramatical errors.