Skip to content

Instantiating Destroying GameObjects Over The Network

Ryan edited this page Jun 27, 2020 · 2 revisions

Instantiating/Destroying GameObjects Over The Network

Prefab Domains/IDs

To Instantiate/Destroy any GameObjects you must first have a "NetworkData" component attached to a GameObject somewhere during runtime. The server and client(s) must both know what prefab you want to be created, so to do this you must assign the prefab a domain and ID, this is very simple.

Simply increase the size of Network Prefab List within the NetworkData component in the editor. Expand the new element, name it whatever you please. So if you are putting structures in it, name it structures. Then you simple add the prefabs to the prefab list.

How the prefab domain works, is the domain is the index of the prefab list within the NetworkData object. Then the prefab ID is the index of the prefab within Prefab List.

Instantiating

Creating a prefab over the network is very simple. Instead of having to manually write the packet over the server all you need to do is use a public static method within NetTools.

NetTools.NetInstantiate(prefabDomain,prefabID,position,rotation);

There is also sT for the send type. Check the "Packet Type" page on the wiki for more info, however it defaults to a buffered packet. As well as there is isSharedObject which is false by default, it'll allow anyone to edit the object over the network.

When an object gets created over the network a NetworkObject component gets attached if one isn't already on it. As well as it is assigned a network ID so both the client/server know what it is talking about.

Destroying

Destroying is similar to Instantiating. Instead of you having to manually write and send the packet. All you need to do is use a public static method in NetTools.

NetTools.NetDestroy(NetworkObject net);

NetTools.NetDestroy(int networkID)

When an object gets created over the network a NetworkObject component gets attached if one isn't already on it. As well as it is assigned a network ID so both the client/server know what it is talking about.

There is also sT for the send type. Check the "Packet Type" page on the wiki for more info, however it defaults to a buffered packet.

Advanced Instantiating

Let's say not only do you need to instantiate an object but in the same frame set a network ID and it cant wait any frames to be done. You can pack a bunch of "NetworkFieldPackets" inside of the instantiation and it'll execute them immediately after instantiating the prefab.

You simply need to pass the variable fieldDefaults into NetTools.NetInstantiate. You pass it as a List of NetworkFieldPackets.

There is no need to manually code the NetworkFieldPacket each time either. You can use NetworkField.GenerateNFP(fieldName, newValue); you can even pass immediateOnSelf, which is false by default.

Clone this wiki locally