Hey all
Pretty new to Netcode, so please have patience with me understanding it.
I have a test scene with gameobjects, that when pressing E, get destroyed. Of course this works great when not using Netcode. Now, I want that if a client destroys one of these gameobjects, it is synced to the server and from there to the other clients. The gameobjects already exist in the scene upon spawning the players, meaning they are server owned. They all have a NetworkObject component.
My code looks like this:
Method of script that is called to invoke the destroy:
protected override Task Run(Args args)
{
NetworkObject networkObject = this.m_GameObject.Get(args).GetComponent<NetworkObject>();
NetworkManager.Singleton.GetComponent<NetworkGameObjectHandling>().HandleGameObjects(GameObjectOperation.Destroy, networkObject.NetworkObjectId);
return DefaultResult;
}
The two methods in the NetworkGameObjectHandling script that is on the NetworkManager gameobject which should tell the server to destroy the gameobject:
public void HandleGameObjects(GameObjectOperation operation, ulong networkId)
{
switch (operation)
{
case GameObjectOperation.Instantiate:
break;
case GameObjectOperation.Destroy:
UnityEngine.Debug.Log(UnityEngine.GameObject.FindObjectsOfType<NetworkObject>().Where(n => n.NetworkObjectId == networkId).FirstOrDefault().IsOwnedByServer);
DespawnGameObjectServerRpc(networkId);
break;
}
}
[ServerRpc]
public void DespawnGameObjectServerRpc(ulong networkId)
{
NetworkObject networkObject = UnityEngine.GameObject.FindObjectsOfType<NetworkObject>().Where(n => n.NetworkObjectId == networkId).FirstOrDefault();
UnityEngine.Debug.Log(networkObject.NetworkManager);
if (networkObject != null) Destroy(networkObject);
}
I get the error message “Only the owner can invoke a ServerRpc that requires ownership!”, meaning I am doing something terribly wrong, I am sure.
If someone can enlighten me with his knowledge please, I am truly grateful if I knew how to do this