Skip to content

Network Fields

Ryan edited this page Jul 13, 2020 · 3 revisions

Network Fields

Setup

Network Fields are very useful. Entity Networking Systems (ENS) completely handles them for you. They are variables attached to a GameObject's NetworkObject component that automatically get updated for all clients/server when changed.

NetworkObject is automatically added to any GameObject created over the network, however if added to the prefab, it allows you to have Network Fields as well as RPCs (See RPCs in the wiki for more information).

Creating A Field

To create a network field, you simply go to the NetworkObject of your choosing, go to fields and add a field. You must assign the field a name. You don't need to assign a default value, however you can, if you don't make sure you set it up manually somewhere in an object's Start().

You can also create a field in code.

NetworkObject.CreateField(fieldName, value, init=NetworkField.valueInitializer.None);

Creating a field like this does not make it get created over the network, so make sure it gets created on all clients/server.

Editing A Field

Now that is it setup and created you can simply edit it. Only clients with authority over the object or the server can edit them. Check Server Authority in the wiki for more information.

NetworkObject.UpdateField(fieldName, value);

Simply use NetworkObject.UpdateField to update the field for you and everyone else.

NetworkObject.GetField(fieldName);

This will return the field's value as type "object". Then you will need to cast it to whatever it should be. When I have time, or if someone wants to contribute having it able to return certain types would be helpful instead of just object.

OnValueChange

If you look in a NetworkObject component and it's Network Fields, there is a UnityEvent called OnValueChange. When triggered it passes the methods attached a FieldArgs datatype, you can use `FieldArgs.GetValue()' to get the field's info. You can also check for the name, network object ID.

There are some cases where you need to use OnValueChangeMethods instead. In this case you have to input the Component's name and the method's name. Then it'll run it when the NetworkField changes, even passing the FieldArgs to it!

You'd mostly only need to use OnValueChangeMethods when you are updating one of it's NetworkFields right after instantiating it over the network, Since if you use NetworkObject.FieldAddOnChangeMethod() inside of a script's Start/Awake/Etc it may not be ran until after the networkfield gets updated.

Clone this wiki locally