Skip to content

Instantly share code, notes, and snippets.

@James-Frowen
Created October 15, 2020 11:32
Show Gist options
  • Save James-Frowen/b250e65bc4cb63cf8487992f6306374a to your computer and use it in GitHub Desktop.
Save James-Frowen/b250e65bc4cb63cf8487992f6306374a to your computer and use it in GitHub Desktop.

Use scriptable object to refernce object. This doesn't require the object to have spawned, you can just listen for the OnValueChange (and check if value is already set)

Reference

[CreateAssetMenu(fileName = "NetworkIdentityReference", menuName = "Component Reference/NetworkIdentity")]
public class NetworkIdentityReference : ScriptableObject
{
    [SerializeField] NetworkIdentity _value;

    public event Action<NetworkIdentity> OnValueChange;

    public NetworkIdentity Value
    {
        get => _value;
        set
        {
            _value = value;
            OnValueChange?.Invoke(_value);
        }
    }
}

Set Reference

public class SetLocalPlayer : NetworkBehaviour
{
    [SerializeField] NetworkIdentityReference _reference;

    public override void OnStartLocalPlayer()
    {
        // don't destroy player objecct when changing scenes 
        DontDestroyOnLoad(gameObject);

        _reference.Value = netIdentity;
    }
    public override void OnStopClient()
    {
        if (isLocalPlayer)
        {
            _reference.Value = null;
        }
    }
}

Example use of reference

public class UIManager : MonoBehaviour
{
    public NetworkIdentityReference localPlayer;

    void Start()
    {
        localPlayer.OnValueChange += localPlayerChanged;
        localPlayerChanged(localPlayer.Value);
    }

    private void localPlayerChanged(NetworkIdentity obj)
    {
        if (obj != null)
        {
            // setup here
        }
        else
        {
            // tear down here
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment