I'm trying to learn Unity Netcode.
Essentially, a PlayerController will be present on both the host and the client. The PlayerController prefab has the Network Object component, and has been added to the Network Manager. There is a spawnPrefab that instantiates when I hit the space key on the host. The spawnPrefab has the Network Object component and has been added to the Network Manager.
When I hit space on the Host, the prefab is spawned on both the host and client.
However, when I hit the Y key on the client side, I get an error saying that spawnedObjectTransform has not been instantiated. I do not get this error when hitting Y on the host side, there the object is destroyed on both host and client.
Here is the player script. The spawnPrefab GameObject does not have any scripts on it other than Network Object.
public class PlayerController : NetworkBehaviour
{
public GameObject spawnPrefab;
private Transform spawnedObjectTransform;
void Update()
{
// For multiplayer, if not owner, ignore all commands
if (!IsOwner)
return;
if (Input.GetKeyDown(KeyCode.Space))
{
spawnedObjectTransform = Instantiate(spawnPrefab).transform;
spawnedObjectTransform.GetComponent<NetworkObject>().Spawn(true);
}
if (Input.GetKeyDown(KeyCode.Y))
{
TestServerRpc();
}
}
[ServerRpc(RequireOwnership = false)]
private void TestServerRpc()
{
Destroy(spawnedObjectTransform.gameObject);
}
}
The only explanation I can see is that TestServerRpc is somehow only being called on the client side and not on the server. Has anyone else seen something like this?
You are not spawning the object on the server to begin with. Place the instantiation in a separate ServerRpc method and call it using a callback: