Colliders

Summary

Shows how to modify colliders at runtime and sync the changes to clients using properties.

Collider scripts

Each collider has an associated server entity collider script. To get the list of colliders on an entity, use Scripts.GetAll<ksCollider>(). Once you have a reference to a collider script, you can modify its properties.

Enabling/disabling colliders at runtime

There are multiple different ways to enable/disable a collider, as described below.

using System.Collections.Generic;
using KS.Reactor.Server;

public class sColliderController : ksServerEntityScript
{
    public override void Initialize()
    {
        SyncColliderState();
    }

    // Syncs the enabled state of all colliders as a bool array property. Call this after enabling or disabling colliders.
    public void SyncColliderState()
    {
        List<ksCollider> colliders = Scripts.GetAll<ksCollider>();
        bool[] states = new bool[colliders.Count];
        for (int i = 0; i < colliders.Count; i++)
        {
            states[i] = colliders[i].IsEnabled;
        }
        Properties[0] = states;
    }
}

Client Collider Controller Entity Script

using UnityEngine;
using KS.Reactor.Client.Unity;
using KS.Reactor;

public class cColliderController : ksEntityScript
{
    public override void Initialize()
    {
        // When the property changes, change the enabled state of colliders.
        Entity.OnPropertyChange[0] += OnEnabledChange;
        OnEnabledChange(false, Properties[0]);
    }

    public override void Detached()
    {
        Entity.OnPropertyChange[0] -= OnEnabledChange;
    }

    private void OnEnabledChange(ksMultiType oldValue, ksMultiType newValue)
    {
        bool[] states = newValue;
        if (states == null)
        {
            return;
        }
        Collider[] colliders = GetComponents<Collider>();
        for (int i = 0; i < colliders.Length; i++)
        {
            colliders[i].enabled = i < states.Length && states[i];
        }
    }
}