Unet: Spawn bullet - client does not have a reference of bullet

Hi there,

i try to make turrets fire bullets on unet.
It is working for the host but if i shoot on the client it says:
NullReferenceException: Object reference not set to an instance of an object
TurretController.CmdShoot (UnityEngine.GameObject _firePos, UnityEngine.GameObject _shell) (at Assets/Skripts/Player/Turret/TurretController.cs:116)

The shell is registered on the NetworkManager and it is referenced on the Turret itself.

Here is my code so far:

void FixedUpdate()
    {
        ControlTurrets();
    }


    void ControlTurrets()
    {
        for (int i = 0; i < turrets.Length; i++)
        {
            if (turrets *!= null)*

{
Turret _turret = turrets*.GetComponent();*
GameObject _target = _turret.GetTarget();
GameObject _shell = _turret.GetShell();

targetController.SelectTarget(_turret);

Turn(_turret, _target);
Pitch(_turret, _target);

if (Input.GetMouseButtonDown(0))
{
Shoot(_turret, _shell);
}

}
else
{
Debug.LogError(“No turret referenced.”);
}
}
}

[Client]
void Shoot(Turret _turret, GameObject _shell)
{
Debug.Log(gameObject.name + ": " + _shell);

if (!isLocalPlayer)
{
return;
}

Transform _turretHead = _turret.transform.FindChild(“Head”);
GameObject _firePos = _turretHead.transform.FindChild(“FireTransform”).gameObject;

CmdShoot(_firePos, _shell);
}

[Command]
void CmdShoot(GameObject _firePos, GameObject _shell)
{

GameObject shellInstance = Instantiate(_shell, _firePos.transform.position, _firePos.transform.rotation) as GameObject;

// Set the shell’s velocity to the launch force in the fire position’s forward direction.
shellInstance.GetComponent().velocity = shellSpeed * _firePos.transform.forward;

NetworkServer.Spawn(shellInstance);
}
I googled for an answer but i didnt find a solution to my problem :frowning:
It seems like the client is for some reason not getting any reference to the shell Object and i have no idea why that is so

I looked at your project. The problem is that you disable the scripts that handle these calls on the RemotePlayer. As a result on the other client machines and probably the server, they never run the code they need to acquire the shell.

There are a number of problems that are standing in your way. For example passing a GameObject reference through 3 functions in the same script is probably not a good idea. Repeated transform.Find and GetComponent calls in the loop is a bad idea. Get references once and cache them to save on processing. You don’t use enough Attribute tags, like [Server] or [Client] to isolate code or use the isLocalPlayer condition to segment scripts to differentiate between roles in the code.

Also, the use of [SyncVar] can often be preferable to a NetworkTransform. Having many NetworkTransforms on one object may not be desirable.