Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

[Closed] Destroy GameObject, OnEnterTrigger and press key.

Discussion in 'Scripting' started by mysokskycz, Jul 1, 2015.

  1. mysokskycz

    mysokskycz

    Joined:
    May 1, 2015
    Posts:
    4
    Hi,
    i need help with this: when player enter trigger and press "E" ,script destroy the gameobject.
    This is my script, I am using JS and Unity 4.6.1:

    Code (csharp):
    1. #pragma strict
    2. var isText : boolean = false;
    3. var style : GUIStyle;
    4. var item : GameObject;
    5.  
    6. function Start () {
    7. isText = false;
    8. }
    9.  
    10. function OnTriggerEnter (other : Collider) {
    11.   isText = true;
    12.   if(Input.GetKey(KeyCode.E))
    13.   {
    14.   Destroy (item);
    15.   }
    16.   }
    17.   function OnTriggerExit (other : Collider) {
    18.   isText = false;
    19.   }
    20. function OnGUI () {
    21.    if(isText)
    22.         GUI.Label(Rect (Screen.width/2 - 75, Screen.height - 100, 150, 30), "Press E to destroy this", style);
    23. }
     
    Last edited: Jul 1, 2015
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    OnTriggerEnter fires once, in the first frame the player hits the trigger collider. For that code to work the player would need to hit the key at the exact frame...

    use the triggers to set a bool and put the Input.Get... inside the update and check the bool in an if



    also use [code ][/code ] tags when you paste code into the forums, really helps with the readability, there is a sticky on them at the top of the scripting forum
     
    mysokskycz likes this.
  3. GNGification

    GNGification

    Joined:
    Oct 24, 2013
    Posts:
    59
    Or instead of a bool, replace OnTriggerEnter with OnTriggerStay. Both ways do the trick tho.
     
    mysokskycz likes this.
  4. mysokskycz

    mysokskycz

    Joined:
    May 1, 2015
    Posts:
    4
    Thank you ,but how i can add
    Code (csharp):
    1. if(Input.GetKey(KeyCode.E))
    to function update ?
     
  5. GNGification

    GNGification

    Joined:
    Oct 24, 2013
    Posts:
    59
    Just put it inside Update, however with OnTriggerStay you can keep it where it is. OnTriggerStay keeps updating as long as it's triggered.
     
    mysokskycz likes this.
  6. mysokskycz

    mysokskycz

    Joined:
    May 1, 2015
    Posts:
    4
    Wow! it's working now! Very very thank you :)
     
    GNGification likes this.