- Home /
How can I disable a Method.
So I made a script and (we’ll call this script attack_02), and in that script, I made a method…
void OnTriggerEnter2D(Collider2D coll){
if (coll.gameobject.tag == "Enemy") {
Destroy (coll.gameObject);
}
}
This method destroys the Enemy gameobject if the Player’s BoxCollider2D and the Enemy’s BoxCollider2D collided. I decided that I wanted this method to only happen if we hold down the H key, so I did that in another script called “attack_01”. But I enabled/disabled the entire attack_02 script.
1. if (Input.GetKey(KeyCode.H))
2. {
3. attack_02.enabled = true;
4. }
5. else
6. {
7. attack_02.enabled = false;
8. }
I thought I would work and the BoxCollider2D for the Player wouldn’t destroy the Enemy if they collided when the H isn’t held down. But I did, I feel as though me disabling/enabling the script has no effect on the the method(that’s just my theory). By the way I disabled the attack_02 script in the start method ,with this line of code.
19. attack_02.enabled = false;
My Question is pretty the same as the topic question, How can I disable a Method, or if you have any better solutions please help.
Answer by fafase · Sep 17, 2017 at 03:28 PM
bool keyPressed = false;
void Update(){
if (Input.GetKey(KeyCode.H)){ keyPressed = true; }
else if (Input.GetKeyUp(KeyCode.H)) { keyPressed = false;}
}
void OnTriggerEnter2D(Collider2D coll){
if (coll.gameobject.tag == "Enemy" && keyPressed) {
Destroy (coll.gameObject);
}
this uses a boolean to set when key is down. Then in the collision, you check whether it is true/false. You can't really check input in Collision as you could miss some hit.
Uhm checking Get$$anonymous$$ey should work inside OnTriggerEnter2D. It just returns the state of the key, no matter where you check it. So you could simply do
void OnTriggerEnter2D(Collider2D coll){
if (coll.gameobject.tag == "Enemy" && Input.Get$$anonymous$$ey($$anonymous$$eyCode.H) ) {
Destroy (coll.gameObject);
}
Of course things like Get$$anonymous$$eyDown or Get$$anonymous$$eyUp won't work in OnTriggerEnter but it would work in OnTriggerStay.
It does work in this case but since Input and Physics are not aligned it is often better not to start putting input in physics method. That is for those checking Up/Down.
@fafase thanx but your script isn't what I was looking for
Your answer
Follow this Question
Related Questions
What happened to Line Renderer! 1 Answer
Add audio. 1 Answer
How can I flip only my 'Player' gameobject, and l leave it's child object alone? 2 Answers
Don't Flip Child, Only Parent. 0 Answers
Jumping isn't smooth while going up 1 Answer