Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Join us on Thursday, June 8, for a Q&A with Unity's Content Pipeline group here on the forum, and on the Unity Discord, and discuss topics around Content Build, Import Workflows, Asset Database, and Addressables!
    Dismiss Notice

Question Interaction System | Change behaviour depending on object type

Discussion in 'Scripting' started by lucasthier2015, Mar 26, 2023.

  1. lucasthier2015


    Sep 1, 2022
    Hi, im making an interaction system for my game.
    Every object that you can interact with has an InteractionReceiver script which has some methods like Onhover(), OnInteract(), OnHold(), etc.
    I made an interactionHandler script for the player that basicaly performs a raycast forward to determine if its looking at something and then checks if that GameObject has an InteractionReceiver script using TryGetComponent.
    Im trying to have different behaviors depending on what object it is, for example if its a door, show "Press E to open" when hovering over it but if it is a dropped item I want to show "Press E to Pick Up".
    I am having trouble to get a way of changing for example, what OnHover() does depending on the item. Im also interested on making it so that the client only has to call those functions and not making 100 ifs to check what type of object im looking at. also i need to make it so that i can change the behaviour of all the items of the same type at once from one script.
    Any ideas on how can I achive this?
  2. spiney199


    Feb 11, 2021
    This is a case where this functionality needs to embedded within the objects, and object interacting with them has no idea/care about what they do. Easily done with interfaces.

    Define an interface for these interactables. Such as this:
    Code (CSharp):
    1. public interface IInteractable
    2. {
    3.    string InteractionPopup { get; }
    5.    void OnHover();
    7.    void OnInteract();
    9.    void OnHold();
    10. }
    Then any number of components can implement this, and define their own functionality inside these methods. Then you only need to
    TryGetComponent(out IInteractable interactable)
    to call its behaviour. Same with the message, as all
    's can define a string property for what message they should display.
    lucasthier2015 likes this.
  3. Olipool


    Feb 8, 2015
    I would second that, it makes your system very flexible and extensible. Also very clean and keeps those messy "if item instanceof TypeA" out of the code. If you need a common behavior between all interactable objects you can also take a look into abstract classes (but it seems to me, an interface is sufficient).