Search Unity

Question How to add new Input Action to Unity 3D Third Person template that other scripts can detect?

Discussion in 'Input System' started by SeP_Unity, Feb 5, 2023.

  1. SeP_Unity

    SeP_Unity

    Joined:
    Mar 6, 2022
    Posts:
    1
    Hi!

    I'm trying to prototype something using the Unity 3D Third Person template, and I've run into a bit of a snag adding a new input action.

    Essentially, I'm trying to add an "interact" button that will trigger things like dialogue or inspecting an object in the game.

    I think I'm most of the way there. I added an Input Action for "Interact". I bound it to a keyboard key. Then, I added an InteractInput and OnInteract method in the StarterAssetsInputs class. If I test the "Interact" button on the Third Person Controller class, it works as I expected and I can trigger methods from there.

    However, I would like to be able to check if "Interact" has been pressed from other scripts that aren't the Third Person Controller class, and I'm unsure how to do that. To give an example- I'd like to put a script on an "NPC" game object, which would check if the player is near that object and check if the interact button is being pressed, which would then trigger dialogue.

    I tested this on a script, mimicking as much of the code from the Third Person Controller class as I thought was necessary. It compiles, but on runtime I'm faced with an error: "NullReferenceException: Object reference not set to an instance of an object."


    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.InputSystem;

    namespace StarterAssets
    {
    public class testInteractScript : MonoBehaviour
    {
    private StarterAssetsInputs _input;

    void Start()
    {
    _input = GetComponent<StarterAssetsInputs>();
    }

    void Update()
    {
    if (_input.interact)
    {
    Debug.Log("Interact has been pressed by the player.");
    _input.interact = false;
    }
    }
    }
    }


    Apologies if this is a stupid question or has an easy answer. I'm new to coding and Unity, and I tried to look through the documentation but I could only find things about adding Input Actions specifically to the player, like "Fire".

    TLDR: How do I detect if an Input Action is being pressed from a script other than the Player itself?

    Thanks!