Using NetworkColliders
Using each NetworkCollider component is the same, and can be used very similar to Unity callbacks.
Callbacks
Usage
// We are assuming this script inherits NetworkBehaviour.
[SerializeField]
private AudioSource _hitSound;
private NetworkCollision _networkCollision;
private void Awake()
{
// Get the NetworkCollision component placed on this object.
// You can place the component anywhere you would normally
// use Unity collider callbacks!
_networkCollision = GetComponent<NetworkCollision>();
// Subscribe to the desired collision event
_networkCollision.OnEnter += NetworkCollisionEnter;
_networkCollision.OnStay += NetworkCollisionStay;
_networkCollision.OnExit += NetworkCollisionExit;
}
private void OnDestroy()
{
// Since the NetworkCollider is placed on the same object as
// this script we do not need to unsubscribe; the callbacks
// will be destroyed with the object.
// But if your NetworkCollider resides on another object you
// likely will want to unsubscribe to your events as well as shown.
if (_networkCollision != null)
{
_networkCollision.OnEnter -= NetworkCollisionEnter;
_networkCollision.OnStay -= NetworkCollisionStay;
_networkCollision.OnExit -= NetworkCollisionExit;
}
}
private void NetworkCollisionEnter(Collider other)
{
// Only play the sound effect when not currently reconciling.
// If you were to play the sound also during reconciliations
// the audio would execute each reconcile, each tick, until the
// player was no longer reconciling into the collider.
if (!base.PredictionManager.IsReconciling)
_hitSound.Play();
// Always apply velocity to this player on enter, even if reconciling.
PlayerMover pm = GetComponent<PlayerMover>();
// For this example we are pushing away from the other object.
Vector3 dir = (transform.position - other.gameObject.transform).normalized;
pm.PredictionRigidbody.AddForce(dir * 50f, ForceMode.Impulse);
}
private void NetworkCollisionStay(Collider other)
{
// Handle collision stay logic
}
private void NetworkCollisionExit(Collider other)
{
// Handle collision exit logic (e.g., deactivate visual effects)
}Last updated