If script not working as expected - camera switch
I have been working for a couple of days on the script below and it compiles without error. However, when I am close to the object and press E...nothing happens, no cam,era switch, no debug log... It's like the IF statement never actually completes / runs.
var hasCollided:boolean = false;
var labelText:String = "";
var cam1 : Camera;
var cam2 : Camera;
function Start () {
cam1.enabled = true;
cam2.enabled = false;
}
function OnGUI()
{
if (hasCollided ==true)
{
GUI.Box(Rect(140,Screen.height-50,Screen.width-300,120),(labelText));
}
}
function OnTriggerEnter(c:Collider)
{
if(c.gameObject.tag =="Player")
{
hasCollided = true;
labelText = "Press E to access the console";
if (Input.GetKeyUp(KeyCode.E))
{
cam1.enabled = !cam1.enabled;
cam2.enabled = !cam2.enabled;
Debug.writeln = "E Key Pressed.";
}
}
}
function OnTriggerExit( other : Collider ){
hasCollided = false;
}
This is JavaScript and any help would be appropriated.
Thanks, Phill
suggest an additional debug line at the top of the function, before any if's: confirm the code is being run at all.
Answer by termway · Feb 26, 2016 at 07:53 PM
Input.GetKeyUp is only valid during the frame the user releases the key. There is a high probabilty that it won't be in the same frame of your OnTriggerEnter event.
Two solutions: Use update function to manage your Input.
void Update()
{
if (hasCollided && Input.GetKeyUp(KeyCode.E))
{
cam1.enabled = !cam1.enabled;
cam2.enabled = !cam2.enabled;
Debug.writeln = "E Key Pressed.";
}
}
Or use OnTriggerStay() instead of OnTriggerEnter() which is call as long as you are colliding.
Your answer
Follow this Question
Related Questions
With the following script i wanted to activate a collider at the left/right side... 0 Answers
How to turn turn off/on a collider with a boolean from another script 1 Answer
How to add avoid the script to overwrite camera collision? 0 Answers
How to rotate camera view? 0 Answers
If you collide with an object destroy the object updated for unity 5 ? 3 Answers