NetworkGameObjects - CaptainToTo/owl-tree-unity GitHub Wiki
NetworkGameObjects
In order to identify gameobjects across clients, gameobjects instantiated using a UnityConnection's Spawn(prefab) method will have a NetworkGameObject component attached to the root gameobject of the prefab. This component will be assigned a GameObjectId which uniquely identifies it, and can be used to find the object using either the UnityConnection's GetGameObject(), or the generic object map of the OwlTree Connection it wraps.
GameObjectId id = new GameObjectId(1);
// via unity connection
NetworkGameObject obj = unityConnection.GetGameObject(id);
// via generic object map
Connection connection = unityConnection.Connection;
NetworkGameObject obj = connection.Maps.Get(id);
NetworkGameObjects also provide OnSpawn and OnDespawn unity events. These are similar to Unity's Awake() and OnDestroy() methods, but are attach to network events. This means you can have separate initialization and clean-up logic for whether a gameobject is networked on not.
public class MyScript : MonoBehaviour
{
void Awake()
{
// will always be called, initialize things essential to both single- and multi-player
}
// subscribe to NetworkGameObject's OnSpawn event in inspector
public void OnSpawn(NetworkGameObject obj)
{
// will only be called if instantiated by a connection, initialize multiplayer specific things
// invoked after Awake()
}
void Start()
{
// will always be called, invoked after OnSpawn()
// use to initialize single-player specific things based on whether OnSpawn was invoked
}
// subscribe to NetworkGameObject's OnDespawn event in inspector
public void OnDespawn(NetworkGameObject obj)
{
// will only be called if destroyed by a connection, clean up multiplayer specific things
}
void OnDestroy()
{
// will always be called, clean-up things that will be in both single- and multi-player
// invoked after OnDespawn()
}
}
At Awake() the NetworkGameObject will not be set up yet, meaning it will not have a GameObjectId assigned, and it won't have a reference to the UnityConnection that manages it. By OnSpawn() the NetworkGameObject will be fully initialized. You can observe its initialization state with the IsActive member.
if (networkGameObject.IsActive)
Debug.Log(networkGameObject.Id); // print its GameObjectId
if (networkGameObject.Connection.IsAuthority) // reference to the UnityConnection managing it
Debug.Log("is authority");