Is it possible to allow client to spawn network object ?

Hi guys,

I’m running into some issue with netcode. I’m making an multiplayer fps and bullets are rigidbody.

when the host shoot, it’s working fine, no issue what so ever, but the client have this error when trying to spawn a network object:

NotServerException: Only server can spawn NetworkObjects

here is the piece of code

    public void Shoot(Vector3 raycastHit)
    {
        bulletSpawnPoint.LookAt(raycastHit, bulletSpawnPoint.forward);
        Transform bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation);
        bullet.GetComponent<Rigidbody>().velocity = bulletSpawnPoint.forward * bulletSpeed;
        bullet.GetComponent<NetworkObject>().Spawn(true); //error is at this line
    }

is there a way to allow client to spawn network objects in the overall project ? or do I have to make a serverRPC ?
(I’m trusting clients since this will be a game to play with friends)

thanks you !

Yes, you will have to make a ServerRpc to do the spawning.

1 Like

yeah that what I did, thanks you.

for some reason when a client spawns an object using serverrpc i still get the error “NotServerException: Only server can spawn NetworkObjects”. Any ideas why?


[ServerRpc]
private void InitCraftedPrefabServerRpc(string craftPrefab, Vector3 position, Quaternion rotation, bool enableClip)
{
GameObject prefab = Instantiate(Resources.Load(craftPrefab)) as GameObject;
prefab.transform.position = position;
prefab.transform.rotation = rotation;
prefab.GetComponent<NetworkObject>().Spawn();
}

Are you sure the exception originates from that piece of code? At a first glance, everthing there seems fine

Does the ServerRpc need ServerRpcParams defined to be utilized correctly and run on the server?

eg.
private void InitCraftedPrefabServerRpc(string craftPrefab, Vector3 position, Quaternion rotation, bool enableClip, ServerRpcParams rpcParams = default)

Nope

Is your class deriving from NetworkBehaviour?

Have you solved this problem?

It looks like it does need to derived from Network behavior to work, however attempting to do so generates another error:
KeyNotFoundException: The given key ‘[KEY]’ was not present in the dictionary.
This occurs on the line where you try to instantiate the prefab, anyone know why this occurs?