#59 - Unity base Interactable script

Data: 2019-05-04 12:00 - c#

Script for unity to make an object interactable. Needs to be extended to implement the OnInteract method.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class Interactable : MonoBehaviour {
    public float interactionDistance = 1;
    private new Collider collider;

    void Start() {
        collider = GetComponent<Collider>();
    }

    void Update() {
    }

    public void TryInteract(GameObject caller) {
        if (CanInteract(caller))
            OnInteract(caller);
    }

    public virtual bool CanInteract(GameObject other) {
        return true;
    }

    abstract public void OnInteract(GameObject other);

    void OnDrawGizmosSelected() {
        if (collider == null) {
            Start();
        }

        Vector3 center = collider.bounds.center;
        Gizmos.DrawWireSphere(center, interactionDistance);
    }
}

Previous snippet | Next snippet