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?