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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Creating a first Person Interaction system

Discussion in 'Scripting' started by Shadowboi, May 2, 2020.

  1. Shadowboi

    Shadowboi

    Joined:
    Jan 26, 2020
    Posts:
    9
    Hey guys. I'm trying to create a first person interaction system where the player is able to interact with various game objects and implementing different behaviours depending on what is being interacted with. For example, if there's a pickup on the ground, the character should be able to look at it and pick it up with the press of a button or if there's a door, the character should be able to use the same button to open the door.

    What's the best way to go about doing this?

    Currently, what I'm doing so far is using a raycast script to be able to detect items and using tags on game objects to determine what should happen when I press a button but this means all of my code for interactions ends up being on the one raycast script and I don't know how feasible this would be if there are many different interactable objects in my game that do different things.
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    What I would probably do is make an interface called Interactable that has the following methods:
    Code (CSharp):
    1. // Allows interactables to decide if they are currently interactable
    2. bool IsCurrentlyInteractable();
    3.  
    4. // Allows the interactable to decide what text to appear when the player looks at it
    5. string LookAtText();
    6.  
    7. // What happens when the player interacts with this interactable?
    8. void Interact();
    Then I would make sure all of my interactable objects implement this interface. Now your raycast script just has to do the following when it sees an object:
    1. GetComponent<Interactable>() to get the interactable component from the object. If it is null, return
    2. Check if IsCurrentlyInteractable() == true. If not, return
    3. Show the LookAtText() from the interactable on screen when the player is looking at an interactable
    4. If the player presses the interaction button, just call the OnInteract() method on the interactable
    This way you can define the actual behavior in the individual interactable item scripts, but leave the raycast/interaction behavior the same for all.
     
  3. Shadowboi

    Shadowboi

    Joined:
    Jan 26, 2020
    Posts:
    9
    Thank you for the advice! This worked well! However, I'm still really nooby and couldn't figure out how to set the bool 'IsCurrentlyInteractable' to true on my interactable objects.