Best way to handle a lot of Interaction 3D

Hello there,
I am currently working on a 3D game, and was wondering how I should go about handling alot of interacting with objects, this includes; Doors, cabinets, drawers and picking up objects. I established that raycasting generally was a good way, but I had all of the interaction in one single script, which quickly caused a bunch of variables, and wasn’t really working the way it should. So, my question is.
If I am in a 3D space, and is interacting with objecs via Raycasting. What is the best way to handle all of the objects respond to me touching them.
Thank you for your time :slight_smile:

This is a vague question but I’ll try to oblige. Personally, I use C# and would use inheritance to define a general base object with general virtual methods, allowing subclasses to override them with specific functionality - this is called Polymorphism.

For example, you could have a base script called UsableObject with methods GetDescription to return a string and Use to perform an action. Then create subclasses for each object, for instance:

  • Door, that inherits from UsableObject and overrides GetDescription to return “Open the Door” and Use would animate the door to open it.
  • Doorbell that returns “Ring the doorbell” in GetDescription, and plays a sound in the overriden Use.

In this way, you can get the object by raycasting, get the description of an action and perform the action without needing to know exactly what the object is that you are interacting with. This also provides the benefit of keeping each script small and contained.

I hope that helps =)

Here’s an example of a base class. This will be a component that you won’t really add to any gameObject. This is where you will add anything that ALL the usable objects have in common.

    public class UsableObject : Monobehavior
    {
        public virtual void Use()
        {
            Debug.Log("UsableObject.Use");
        }
    }

Now for an example subclass for a door - this will live on a the door gameObject.

    public class Door : UsableObject
    {
        public override void Use()
        {
            base.Use(); // Calls UsableObject.Use
            Debug.Log("Door.Use");
        }
    }

Now when you raycast inside the player script for an object you can check if it is a usable object with the GetComponent (if the Door component is at the same level as the collider):

    UsableObject obj = GetComponent<UsableObject>();
    if(obj)
    {
       obj.Use();
    }
    else
    {
       Debug.Log("The object is not a UsableObject");
    }