Best interaction practices

So currently I have my (2d) interaction set up like this:

My setup:
Player has a trigger circle collider.
OnTriggerEnter places other.gameObject in a list if other.CompareTag(“interactable”)
OnTriggerExit removes it.
Update calculates the closest gameObject and saves it as a separate variable.
Update also checks if I’ve pressed F.
If I indeed did and I have a saved closest gameObject:

closestInteractable.GetComponent<Interactable>().OnInteraction(gameObject);

My questions/problems:
Does this method look fine up until the actual interaction or is there a better practice for this?

How could I replace the OnInteraction part?
I have several problems with it:

I do not know how to enforce all interactable objects to have the Interactable script/class. There has to be a way to tell the game that it has to define that method, like an interface.
This way I would have to define to all interactions in a single script, so far I’ve only set up the part to handle money interactions and it’s already getting clunky:

[Header("Options")]
[SerializeField] private int _moneyAmount = 0;
[SerializeField] private bool _destroyOnInteract = false;
[SerializeField] private bool _destroyOnEmpty = false;

[Header("References")]
[SerializeField] private MoneyOptions moneyOptions = null;

And these are just the variables…
If I would make an apple now that you could pick up, half of the code would already be just clutter to that item, because an apple has no connection to money whatsoever.

My original idea was to make an interactable prefab, then set the sprite and script values on the instances, but the code would look like hell with more options than Unity has itself. Then I would have more problems when I want to expand and have slightly different variations of things.

TL;DR:
Is the way I’m detecting and handling close interactable objects good? Is there a better way?
How do I enforce the definition of OnInteraction on certain objects?
How do I make a universal factory of interactable objects?

Thanks in advance!

EDIT:
After further research (Because of course I find a possible solution after I post my question after 2 days of researching and testing…), it seems that a way to go about this would be:

public abstract class Interactable : MonoBehavior {
    // common options/variables

    public abstract void OnInteract();
}

public class InteractableMoney : Interactable {
    // money specific things
}

Then I would make a prefab of a money that’s set up.

Is this the correct way to go or is there a better way?

1 Like

Instead of checking for the “interactable” tag, just check if there’s an interactable object there:

    private void OnTriggerEnter2D(Collider2D other) {
        if (other.TryGetComponent<Interactable>(out var interactable)) {
            interactables.Add(interactable);
        }
    }
// 2018.4 version, where TryGetComponent doesn't exist:
    private void OnTriggerEnter2D(Collider2D other) {
        var interactable = other.GetComponent<Interactable>();
        if (interactable != null) {
            interactables.Add(interactable);
        }
    }

You can also use an interface (IInteractable), as GetComponent/TryGetComponent works with interfaces.

The big problem with your approach is that if you deactivate the interactor object, and then move it, you won’t get OnTriggerExit calls. Probably - that’s how it works in 3D, not quite sure about 2D. So in those cases, you’ll have things in your list that’s actually outside the collider.

You can solve that either by manually purging the list at times when that happens, or by dropping the list and instead using an overlap circle whenever you press interact.

1 Like

This is genius and much simpler, thank you!

I think I cannot drop the list since if 2 items are in range to be interacted with, I still have to keep track of which one is closer, since I can keep them in range while moving closer from item1 to item2.

However so far I’ve used Object.Destroy(gameObject) on the interactable item, which is either smart enough to kill my reference or triggers OnTriggerExit2D.
But nice catch, I’ll keep this mind.
I could also just remove the interactable from the list on use via checking if it will be disabled, something like interactable.disableOnInteract

Thanks again!

I didn’t know TryGetComponent would be faster than CompareTag :hushed:
About how to remove it from the List if it’s destroyed before OnTriggerExit:
If your List of Interactable is static, you can remove them from the list with

private void OnDestroy()
{
    Player.interactables.Remove(this);
}

If you’ve more than one instance you could do it with a Func delegate like this

    private void OnTriggerEnter2D(Collider2D other) {
        if (other.TryGetComponent<Interactable>(out var interactable)) {
            interactables.Add(interactable);
            interactable.func += interactables.Remove;
        }
    }

    private void OnTriggerExit2D(Collider2D other) {
        other.GetComponent<Interactable>(out var interactable);
        interactables.Remove(interactable);
        interactable.func -= interactables.Remove;      
    }
public abstract class Interactable : MonoBehavior {

    public Func<Interactable, bool> func;
    public abstract void OnInteract();

    protected void OnDestroy()
    {
        func();
    }
}

I don’t know if it’s faster, it is a lot simpler to implement though.

Thanks, but as I said:

Unity seems to do this automatically :slight_smile:

Well no sure about what reference to OnTriggerEnter2D you talk about. I’m talking about the list of interactables you have. When you loop through it to see whos the closest one… if some Item of the list has been destroyed without remove it (Transform, Interactable, GameObject or whatever the list is) you will get a missing reference exception if you want to search some value inside it. For example:

public List<Transform> items = new List<Transform>();
foreach(Transform item in items)
{
    Debug.Log(item.position);
}

I could have misunderstood you, but I’m 100% sure unity doesn’t remove all references some Object has at Lists or any Collection type automatically when you call OnDestroy(); Unity knows the object has been destroyed, but if you try to access it, it breaks;

Hmn, interesting.

I do exactly that, however it doesn’t seem to break.

PlayerController.cs (just the parts that matter)

    private List<GameObject> closeInteractables = new List<GameObject>();
    private GameObject closestInteractable;

    private void OnTriggerEnter2D(Collider2D other) {
        if (other.CompareTag("Interactable")) {
            closeInteractables.Add(other.gameObject);
        }
    }

    private void OnTriggerExit2D(Collider2D other) {
        if (closeInteractables.Contains(other.gameObject)) {
            closeInteractables.Remove(other.gameObject);
        }
    }

    private void ProcessInput() {
        ProcessMovement();
        ProcessInteraction();
    }

    private void ProcessInteraction() {
        if (
            Keyboard.current.fKey.wasPressedThisFrame &&
            closestInteractable &&
            closestInteractable.TryGetComponent<Interactable>(out Interactable interactable)
        ) {
            interactable.OnInteract(gameObject);
        }
    }

    private void SetClosestInteractable() {
        GameObject closest = null;
        float closestDistance = 0f;

        foreach (GameObject item in closeInteractables) {
            float newDistance = Vector2.Distance(gameObject.transform.position, item.transform.position);
            if (closest == null || newDistance < closestDistance) {
                closest = item;
                closestDistance = newDistance;
            }
        }

        closestInteractable = closest;

        interactionIndicator.SetActive(closestInteractable != null);
        if (closestInteractable != null) {
            interactionIndicator.transform.position = new Vector2(
                closestInteractable.transform.position.x,
                closestInteractable.transform.position.y +
                    closestInteractable.GetComponent<SpriteRenderer>().bounds.extents.y +
                    0.25f
            );
        }
    }

InteractableMoney.OnInteract:

    public override void OnInteract(GameObject interactee) {
        if (_moneyAmount > 0) {
            GiveCash();
            if (_destroyOnInteract)
                GameObject.Destroy(gameObject);
        }
    }

TL;DR: Only OnTriggerExit2D removes from the list and nothing redefines it.

I went on a few test runs with the list set to public and even in the editor, everything seems to work.

If you destroy at inspector one object at closeInteractables list you’ve not a Missing Reference Exception? So weird.

Apart from this just 2 tips:

//This calcs a root square to give you the distance
Vector2.Distance(gameObject.transform.position, item.transform.position);

//This doesn't calc the root square and gives you distance^2
(gameObject.transform.position - item.transform.position).sqrMagnitude;

Since you doesn’t need the distance value (you only need to know if it’s bigger) you save the machine to calc a bunch of square roots (they’re expensive).

And if:

float closestDistance = Mathf.Infinity;

You don’t need to ensure about if closest == null each loop

if (/** closest == null || */ newDistance < closestDistance) {

No, I mean I displayed the list on the editor and the object is removed from the list as soon as I call Object.Destroy() on it in the script.
Removing the object through the editor results in a MissingReferenceException.
However I don’t plan on anyone playing the game through Unity’s editor :slight_smile:

Huh, good to know!

Smart :slight_smile:

Thanks!