UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"Make objects interactable with a player when he press E to do something add comments to code"
using UnityEngine; public class InteractableObject : MonoBehaviour { public float interactDistance = 3f; // The distance within which the player can interact with the object private Transform player; // Reference to the player's transform // Start is called before the first frame update void Start() { player = GameObject.FindGameObjectWithTag("Player").transform; // Find the player in the scene } // Update is called once per frame void Update() { // Calculate the distance between the player and the object float distance = Vector3.Distance(player.position, transform.position); // Check if the player is within the interactable distance and pressing the 'E' key if (distance <= interactDistance && Input.GetKeyDown(KeyCode.E)) { Interact(); // Call the Interact function } } // The function that handles interaction with the object void Interact() { // Perform the desired action when the object is interacted with Debug.Log("Interacted with " + gameObject.name); } }