- Home /
Question by
AW0610AUT · Jan 04, 2014 at 07:15 PM ·
javascriptcollidertrigger
Script not responding to key press immediately.
Hello, so i have this script and it works, it does everything i want it too however i have to slam the F key a bunch to make it work. a single button press does nothing.
var inside : boolean = false;
var Tooltip : Texture2D;
var TerminalOpen : boolean = false;
var TerminalBackground : Texture2D;
function OnTriggerEnter (col : Collider)
{
if(col.gameObject.name == "Player")
{
inside = true;
}
}
function OnTriggerStay (col : Collider)
{
if(col.gameObject.name == "Player")
{
if (Input.GetKeyDown(KeyCode.F))
{
TerminalOpen = true;
}
}
}
function OnTriggerExit (col : Collider)
{
if(col.gameObject.name == "Player")
{
inside = false;
TerminalOpen = false;
}
}
function Update ()
{
if (TerminalOpen == true)
{
Screen.showCursor = true;
Screen.lockCursor = false;
GameObject.Find("Player").GetComponent("MouseLook").enabled = false;
GameObject.Find("Player").GetComponent("Healthbar").enabled = false;
GameObject.Find("Player").GetComponent("EnergyBar").enabled = false;
GameObject.Find("Main Camera").GetComponent("MouseLook").enabled = false;
GameObject.Find("Main Camera").GetComponent("DebugCtrl").enabled = false;
}
else
{
Screen.showCursor = false;
Screen.lockCursor = true;
GameObject.Find("Player").GetComponent("MouseLook").enabled = true;
GameObject.Find("Player").GetComponent("Healthbar").enabled = true;
GameObject.Find("Player").GetComponent("EnergyBar").enabled = true;
GameObject.Find("Main Camera").GetComponent("MouseLook").enabled = true;
GameObject.Find("Main Camera").GetComponent("DebugCtrl").enabled = true;
}
}
function OnGUI()
{
if (inside == true)
{
GUI.Label(Rect(Screen.width/2-128,Screen.height-Screen.height/3,256,64), Tooltip);
}
if (TerminalOpen == true)
{
GUI.Label (Rect(Screen.width/20,Screen.height/20,Screen.width-Screen.width/10,Screen.height-Screen.height/10), TerminalBackground);
Debug.Log (TerminalOpen);
}
}
It feels like it is random sometimes i have to press 5 times sometimes 9-10 times. What could the problem be?
Comment
You might want to consider exposing the player through the inspector, and caching all of those scripts that you use GetComponent to find in your Update loop. Those are very expensive operations. Also, the main camera can always be accessed via Camera.main.
Example:
var player : Player;
private var energyBar : EnergyBar;
private var mouseLook : $$anonymous$$ouseLook;
function Awake()
{
energyBar = player.GetComponent("EnergyBar");
mouseLook = Camera.main.GetComponent("$$anonymous$$ouseLook");
}
function Update()
{
// ...
mouseLook.enabled = energyBar.enabled = !Ter$$anonymous$$alOpen;
// ...
}
Best Answer
Answer by sath · Jan 04, 2014 at 07:28 PM
if on triggerEnter inside=true means that on triggerStay is true again . So in your Update call the
if ((Input.GetKeyDown(KeyCode.F))&&(inside))
{
TerminalOpen = true;
}
not in function OnTriggerStay