What it want this script i made, to do is:
When i enter its collider my controls disable so i can’t move.
That activates a statement so when i have pressed “i” 50 times the controls gets back again.
But it does not work. When i enter the collider and my controls disable
the “i” press does not work.
Can someone help?
#pragma strict
var taps = 0;
var tapNow = false;
function OnTriggerEnter (other : Collider) {
if(other.tag == "Player")
GameObject.Find( "First Person Controller" ).GetComponent(FPSInputController).enabled = false;
GameObject.Find( "First Person Controller" ).GetComponent(CharacterMotor).enabled = false;
tapNow = true;
}
function Activate () {
if(tapNow == true);
if(Input.GetKeyDown("i")) taps = taps+1;
if(taps == 50);
GameObject.Find( "First Person Controller" ).GetComponent(FPSInputController).enabled = true;
GameObject.Find( "First Person Controller" ).GetComponent( CharacterMotor).enabled = true;
}
The code hides some issues that are not obvious unless you indent your code properly.
Let’s have a look with an indented version of your code (it does the same thing).
#pragma strict
var taps = 0;
var tapNow = false;
function OnTriggerEnter (other : Collider) {
if(other.tag == "Player") // Test only branches for one statement.
GameObject.Find( "First Person Controller" ).GetComponent(FPSInputController).enabled = false;
GameObject.Find( "First Person Controller" ).GetComponent(CharacterMotor).enabled = false;
tapNow = true;
}
function Activate () {
if(tapNow == true); // Wrongly placed ;-sign
if(Input.GetKeyDown("i"))
taps = taps + 1;
if(taps == 50); // Wrongly placed ;-sign
GameObject.Find( "First Person Controller" ).GetComponent(FPSInputController).enabled = true;
GameObject.Find( "First Person Controller" ).GetComponent( CharacterMotor).enabled = true;
}
There are a couple of issues that may cause problems. For one, you don’t use bodies for your if-statements so you are only executing the next line of code if the condition is met, and the other lines are executed regardless.
Your if-statements in Activate have statement terminators ;
which basically render the tests useless.
Here is a version that hopefully works better. As you see, I added bracers around the code in the test, forming a block of code. I also made a small refactoring (extracted a method for enabling or disabling the objects scripts).
#pragma strict
var taps = 0;
var tapNow = false;
function OnTriggerEnter (other : Collider) {
if(other.tag == "Player")
{
EnableFirstPersonController(false);
tapNow = true;
}
}
function Activate () {
if(tapNow && Input.GetKeyDown("i"))
{
taps = taps + 1;
if(taps == 50)
{
EnableFirstPersonController(true);
tapNow = false;
}
}
}
function EnableFirstPersonController(state : boolean) {
var fpsController = GameObject.Find( "First Person Controller" );
fpsController.GetComponent(FPSInputController).enabled = state;
fpsController.GetComponent(CharacterMotor).enabled = state;
}