Skip to content

Instantly share code, notes, and snippets.

@James-Frowen
Last active October 10, 2020 22:04
Show Gist options
  • Save James-Frowen/5caef6688ada02603042d9a2efecf550 to your computer and use it in GitHub Desktop.
Save James-Frowen/5caef6688ada02603042d9a2efecf550 to your computer and use it in GitHub Desktop.
Used to sync a referemce to a NetworkIdentity without requiring the object to be spawned when the reference was sent

NetworkIdentityReference can be used for synclists

public class MyBehaviour : NetworkBehaviour
{
    public SyncList<NetworkIdentityReference> others = new SyncList<NetworkIdentityReference>();

    public override void OnStartClient()
    {
        foreach (NetworkIdentity other in others)
        {
            Debug.Log($"this {netId} other {other?.netId}");
        }
    }
}

spawn and add references

NetIdRef clone1 = Instantiate(prefabWithNetIdRef);
NetIdRef clone2 = Instantiate(prefabWithNetIdRef);

NetworkServer.Spawn(clone1.gameObject);
NetworkServer.Spawn(clone2.gameObject);

// reference each other
clone1.others.Add(clone2.netIdentity);
clone2.others.Add(clone1.netIdentity);
namespace Mirror
{
public struct NetworkIdentityReference
{
public uint netid;
NetworkIdentity _identity;
public NetworkIdentityReference(NetworkIdentity identity) : this()
{
Identity = identity;
}
public NetworkIdentity Identity
{
get
{
return NetworkServer.active
? _identity
: NetworkIdentity.spawned[netid];
}
set
{
_identity = value;
netid = value != null
? value.netId
: 0;
}
}
public static implicit operator NetworkIdentity(NetworkIdentityReference identityRef) => identityRef.Identity;
public static implicit operator NetworkIdentityReference(NetworkIdentity identity) => new NetworkIdentityReference(identity);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment