- Home /
How can I check if I pressed F in the class other than Update()? C#
My question maybe is simple, but I have problem with this. I want to my script will send a message to GUIText called showText, which shows text on HUD. My problem is that: When I enter the trigger without pressed F (there is only "Use", which has F key applied to Input Manager), the message is right, but when I press it, the message is still the same. To show my expected message, I must exit the trigger and enter it again, but with hold down F key. This is I want to fix. How can I fix my script to show the other message when I press F key? There's my full code of DoorZone which uses somes variables in other script
using UnityEngine;
using System.Collections;
public class DoorZone : MonoBehaviour {
public bool doorIsOpenAlready = false;
public int pointsRequired = 750;
public GUIText textHints;
bool UsePressed = false;
void Start () {
}
void Update () {
if(Input.GetButton ("Use")){
UsePressed = true;
//Debug.Log ("F is pressed!");
}else{
UsePressed= false;
//Debug.Log ("F is not pressed!");
}
}
void OnTriggerEnter(Collider col){
if(col.gameObject.tag == "Player" && !doorIsOpenAlready){
textHints.SendMessage ("ShowHint", "Would you like to open this door for "+pointsRequired+" points?");
if(UsePressed){
if(Inventory.points >= pointsRequired){
textHints.SendMessage ("TurnOffText");
transform.animation.Play ("doorOpen");
doorIsOpenAlready=true;
Inventory.points = Inventory.points - pointsRequired;
Debug.Log(Inventory.points);
}else{
textHints.SendMessage ("ShowHint", "You haven't got enough money!");
}
}
}
}
void OnTriggerExit(Collider col){
textHints.SendMessage ("TurnOffText");
}
}
Answer by sparkzbarca · Jan 05, 2013 at 08:06 PM
I BELIEVE you mean you wish to be able to press the button near it and get the popup.
OnTriggerEnter IS ONLY CALLED ONCE. WHEN YOU ENTER.
you should change it to OnTriggerStay it will keep running the code as long as they are in the trigger.
Good luck and mark as answered.
I can't believe it was very simple. Thank you so much for help and sorry for not the most polite language.
Answer by Piflik · Jan 05, 2013 at 08:05 PM
Use two booleans. One you set to true OnTriggerEnter, the other OnKeyDown(KeyCode.F). If both are true, you change the message.
The problem is that OnTriggerEnter is only true for one frame. You could also use OnTriggerStay, but this uses more ressources.
Hmmm, I used OnTriggerStay and works fine. Thanks for help