- Home /
Press 'e' key on object? (C#)
Hey all! I have it set up so pressing the e key works, but the problem is, it works anywhere. I tried to have it on a mouse enter event, but for some reason that doesn't work. I'm basic level at C#, currently in a 202 class at my university, if that helps you understand my knowledge base.
Any and all help appreciated! :)
Here's the code I have so far:
using UnityEngine;
using System.Collections;
public class scrNPC01 : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyUp (KeyCode.E)) {
Debug.Log (gameObject.name);
}
}
}
The debug.log is just for testing, but the principle is similar. For using the e key for interacting with objects/npcs.
Answer by MuffinMyst · Dec 01, 2014 at 02:16 AM
umm... there are several ways you can do this. (and I suppose you could even use a mouse enter event) The way I've done similar to what I think you want to do.
You have to put the "OnMouseEnter" into a script that you attach to what ever object that you want to see the name for. For example:
OnMouseEnter(){
Debug.log(gameObject.name);
}
but... if you want avoid attaching this onmouse enter script for every object in your game. You could also try RayCasting.
I think there is a way to Cast a "ray" from your mouse, that will allow you to access information from the object hit with that "ray" You would have this "ray casting" script on your player
You could have it when you click the mouse, or when you mouse over and object and hit a key... (such as e)
This isn't a full working script but might give you some starting ideas, and the link should assist with understanding
Ray ray;
RaycastHit hit;
float distance; // distance you want it to work
if (Input.GetButtonUp( KeyCode.E ) ){
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, hit, distance)){
Debug.log(hit.name);
}
}
I'm not fluent with Rays yet (I have about as much classroom experience as you do, and about a month of fiddling with scripts people provide here.
Answer by jtagamesinfo · Apr 23, 2021 at 07:59 AM
We created a tutorial with a complete working interact system that you can modify or leave it how it is.
Hope this helps!
Your answer
Follow this Question
Related Questions
need teleport script fixed slightly 1 Answer
C# Script Template - how to make custom changes? 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
press e to speek -1 Answers
Health Regen 1 Answer