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.

Interactable best practice

Discussion in 'Visual Scripting' started by FloweryAF, Nov 8, 2020.

  1. FloweryAF

    FloweryAF

    Joined:
    Sep 13, 2020
    Posts:
    12
    This is super basic, I'm really new to game logic and have no clue re:best practices etc

    My game is filled with NPCs you can talk to. (3rd person, controller driven)
    They all share a Flow that is basically a bool made true on trigger enter, false on exit, and upon a button press, if their bool is true they start chatting.

    But it feels pretty inefficient that all my objects are listening to every button press just praying from their bool to be true.

    Is this bad practice? (I guess it doesn't really matter, my game is tiny and working fine as is, I'm just curious)
     
  2. adamgolden

    adamgolden

    Joined:
    Jun 17, 2019
    Posts:
    1,304
    The simplest approach I can think of is to use a single raycast when button is pressed, have a component on each interactable object, then if raycast hit.collider.gameObject.GetComponent<TheComponent>() is not null, call something like theComponent.TalkButtonPressed();

    Edit: if you want to also have a sort of "hover enter" and "hover exit" you would fire the raycast each frame instead, if the hit object is different from previous frame's raycast hit object (or current one is null or there's nothing hit) you call previousComponent.HoverExit() if that's not null, then call HoverEnter() on the new one, then set previousComponent to the new one. This way you get a HoverEnter and HoverExit call which you can use to animate with / change how something looks while hovered etc.

    Edit: corrected/clarified something in the above paragraph
     
    Last edited: Nov 8, 2020
  3. FloweryAF

    FloweryAF

    Joined:
    Sep 13, 2020
    Posts:
    12
    Oh that’s great info. Thank you!
     
    adamgolden likes this.