How do I change the method used for initiating the interaction. Instead of clicking object, check if within a certain radius of an object when you hit a key on your keyboard.
If within 1 unit, the player gets a message that they can press f to interact. When f is pressd, get the object they're close to and handle the interaction the same way.
PS. I'm using box collider.
Here are the script that I found. I tried this but once I start the game and press F key, its working. But I want the player to press the F key once the character is inside the collider of an object.
WorldInteraction
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class WorldInteraction : MonoBehaviour {
NavMeshAgent playerAgent;
void Start() {
playerAgent = GetComponent<NavMeshAgent>();
}
void Update() {
if (Input.GetMouseButtonDown(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) {
GetInteraction();
}
}
void GetInteraction() {
Ray interactionRay = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit interactionInfo;
if(Physics.Raycast(interactionRay, out interactionInfo, Mathf.Infinity)) {
GameObject interactedObject = interactionInfo.collider.gameObject;
if (interactedObject.tag == "Interactable Object") {
interactedObject.GetComponent<Interactable>().MoveToInteraction(playerAgent);
} else {
playerAgent.destination = interactionInfo.point;
}
}
}
}
Interactable
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Interactable : MonoBehaviour {
public NavMeshAgent playerAgent;
public virtual void MoveToInteraction(NavMeshAgent playerAgent) {
this.playerAgent = playerAgent;
playerAgent.destination = this.transform.position;
Interact();
}
public virtual void Interact() {
Debug.Log ("Interacting with base class.");
}
}
NPC
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPC : Interactable {
public override void Interact() {
Debug.Log ("Interacting with NPC.");
}
}