Hello, I am currently building a multiplayer shooting game. This is my PlayerShoot script:
using UnityEngine;
using UnityEngine.Networking;
using System;
using UnityEngine.UI;
[NetworkSettings(channel = 1, sendInterval = 0.001f)]
public class PlayerShoot : NetworkBehaviour {
private string PlayerTag = "Player";
[SerializeField]
private Camera cam;
public Gun Currentgun;
public LayerMask mask;
public ParticleSystem MuzzleFlash;
public GameObject HitEffect;
public AudioSource source;
public GameObject gunObject;
public Animation Anim;
private Reload reload;
void Start () {
reload = GetComponent<Reload>();
if(cam == null)
{
Debug.Log("PlayerShoot: No Camera!");
this.enabled = false;
}
}
void Update () {
if (!isLocalPlayer)
{
return;
}
if(Currentgun != null){
reload.CurrentGun = Currentgun;
}
if (gunObject != null)
{
Anim = gunObject.GetComponent<Animation>();
}
if (PauseMenu.IsOn)
{
return;
}
if(Currentgun == null)
{
return;
}
if(Currentgun.AmmoLeft <= 0)
{
return;
}
if(Currentgun.FireRate <= 0)
{
if (Input.GetButtonDown("Fire1") && Currentgun.AmmoLeft > 0)
{
if (isServer)
{
CmdShoot();
return;
}
CmdShoot();
}
else if (Input.GetButtonUp("Fire1"))
{
CancelInvoke("Shoot");
}
}
else
{
if (Input.GetButtonDown("Fire1") && Currentgun.AmmoLeft > 0)
{
InvokeRepeating("Shoot", 0f, 1 / Currentgun.FireRate);
}
else if (Input.GetButtonUp("Fire1"))
{
CancelInvoke("Shoot");
}
}
}
void OnShoot()
{
source.Play();
MuzzleFlash.Play();
}
void OnHit(Vector3 pos, Vector3 normal)
{
GameObject go = Instantiate(HitEffect, pos, Quaternion.LookRotation(normal));
Destroy(go, 2);
}
[Command]
void CmdShoot()
{
RpcShoot();
}
[ClientRpc]
void RpcShoot()
{
Shoot();
}
void Shoot()
{
if (Anim != null)
{
Anim.Play();
}
if (Currentgun.AmmoLeft <= 0)
{
return;
}
reload.DeductAmmo();
OnShoot();
RaycastHit _hit;
if (Physics.Raycast(cam.transform.position, cam.transform.forward, out _hit, Currentgun.Range))
{
OnHit(_hit.point, _hit.normal);
if (_hit.collider.tag == PlayerTag)
{
Player1 player = _hit.collider.gameObject.GetComponent<Player1>();
player.TakeDamage(Currentgun.Damage, transform.name);
}
}
}
}
This script works fine, but there is a problem: When a client shoots, it goes through the server and the server updates it to all the clients. This process is very slow. When a client presses the “Fire1” input, it would take about 0.5 seconds for him to see the results. Also, as some guns(such as shotguns) need to reload every single time a bullet is fired, but the client would be able to shoot multiple bullets at a time because of the delay. Any workarounds or ways to change the speed of the [command] and the [clientrpc]?
Thanks in advance. Help would be appreciated.