Reputation: 89
I am making an online multiplayer game in Unity with Mirror Networking. In this script I am trying to shoot a bullet by calling, from the client, a command on the server ( CmdFire() ) that instantiate a projectile from a shot position using the rotation of the player camera. The issue that I have is that when I try to shoot a bullet from the client machine he disconnect where if the host tries to shoot the projectile is not visible to the client. This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class Shooter : NetworkBehaviour
{
public GameObject projectilePrefab;
public Transform shootPos;
public Camera playerCamera;
bool canShoot = true;
public AudioSource shotSound;
[Command]
void CmdFire()
{
GameObject projectile = Instantiate(projectilePrefab, shootPos.position, playerCamera.transform.rotation);
NetworkServer.Spawn(projectile);
}
// Update is called once per frame
void Update()
{
if (!hasAuthority) return;
if (Input.GetButton("Fire1"))
{
if (canShoot)
{
canShoot = false;
GenerateRayCast();
CmdFire();
StartCoroutine(FireDelay());
shotSound.Play();
}
}
}
Transform GenerateRayCast()
{
playerCamera = transform.Find("CameraMountPosition").Find("Camera").GetComponent<Camera>();
Ray ray = new Ray(shootPos.transform.position, playerCamera.transform.forward * 500);
Debug.DrawRay(shootPos.transform.position, playerCamera.transform.forward * 500, Color.red, 2f);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Debug.LogError("SERVER: Player shot: " + hit.collider.name);
if (hit.collider.CompareTag("Player"))
{
//deal damage
}
}
return hit.transform;
}
// Cooldown before shooting again
IEnumerator FireDelay()
{
yield return new WaitForSeconds(2);
canShoot = true;
}
}
Upvotes: 2
Views: 2864
Reputation: 89
I ended up changing the whole way the player shoots projectiles.
First of all I avoided using the player camera to understand the direction for spawning the projectile and I used another gameObject that was basically having the same behaviour of the camera but that was placed IN the player prefab.
The other thing I did was using non-network identity projectiles. So i spawned the projectile both in the Client and in the Server.
void Fire()
{
if (!base.hasAuthority) return;
//if is client spawn on here
if (!base.isServer)
{
Projectile p = Instantiate(projectilePrefab, shootPos.position, shootPos.rotation);
}
//spawn on the server
CmdFire(shootPos.position, shootPos.rotation);
}
Upvotes: 1