How do I go about destroying a game object across the whole network in a multiplayer scene in Unity? I can only get it to destroy on the local client and not for everybody else connected. I'm instantiating the object client side at runtime. Any pointers?
Unsurprisingly, the way clients and servers communicate it with messages. Two ways of doing this is with either event messages or action messages. For example, in a first person game, a client might send the server one of two messages:
1: Event message:
- Client: "I am at position XYZ and have fired my gun in direction Rx,Ry,Rz."
- Server message to everyone: "Player Lime has just been killed, user ABC receives 12 points."
Following the server receiving the client's message, it checks whether a hit actually happened and then updates all clients with its decision. If possible, then this is the correct way to do multiplayer. It is however much more expensive to run, as the server needs to "play" the game and make all decisions.
2: Action messages
- Client: "I just fired my gun at Lime, did 12 damage to him and killed him"
- Server to client: "Ok."
- Server to all other clients: "Player ABC just killed Lime."
In this case you are only relaying what happened to the server, which replies with an event message to all clients. This is however easily exploitable, but cheaper to run, since the server simply relays messages to everyone and informs them of what is going on.
Now I'm assuming that the thing which surrounds this gameobject's destruction, involves more fluff than just "the GameObject gets destroyed". It's probably either death or destruction or map pruning or something. So if you're using the event driven approach, then write a method which handles all the events from this event (including the GameObject's destruction). When a message for that event arrives, fire the method. Then ensure the message is sent to all clients. Each of them should proceed to run their own version of this method, destroying their own copy of the GameObject.
If you're using the other approach, then make a simpler method which just destroys the object. The rest of it actually remains the same.