Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Interaction System | Change behaviour depending on object type

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

  1. lucasthier2015

    lucasthier2015

    Joined:
    Sep 1, 2022
    Posts:
    11
    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

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,611
    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; }
    4.    
    5.    void OnHover();
    6.    
    7.    void OnInteract();
    8.    
    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
    IInteractable
    's can define a string property for what message they should display.
     
    lucasthier2015 likes this.
  3. Olipool

    Olipool

    Joined:
    Feb 8, 2015
    Posts:
    320
    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).