- Home /
look at player when button pressed
hi there im trying to make a noc and i want then to look at you when a button is pressed and im trying to set up the buton press first but it doesnt seem to be working what have i done wrong?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class NpcDialog : MonoBehaviour {
public Transform Player;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider col){
if (col.gameObject.tag == "Player") {
if (Input.GetKeyDown (KeyCode.E)) {
transform.LookAt (Player);
}
}
}
}
Answer by Razor1994 · Dec 16, 2018 at 04:13 PM
Since a friend of mine showed me this question as a reference for his problem, i wanted to answer it even though it is a bit older.
You have a bit of a logic error. OnTriggerEnter is only called once when the trigger enters. Your code does work but you have to hit E the moment you enter the trigger. What you could do is assign a bool whenever the player enters / leaves and check for the KeyCode in the update method.
Here is a version that would work for you. Please note that this is not the best way of doing it since the update method will always check for the Keycode even if you are on the other side of the map (if you dont disable the npc at some point).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NpcDialog : MonoBehaviour {
public Transform Player;
private bool PlayerInRange = false;
// Update is called once per frame
void Update ()
{
if(PlayerInRange && Input.GetKeyDown (KeyCode.E))
transform.LookAt (Player);
}
void OnTriggerEnter(Collider col)
{
if(col.gameObject.tag == "Player")
PlayerInRange = true;
}
void OnTriggerExit(Collider col)
{
if(col.gameObject.tag == "Player")
PlayerInRange = false;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612121306im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
rotate on the Y axis 1 Answer
LookAt once 0 Answers
Lock rotation axis? 4 Answers
LookAt Problem 1 Answer