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. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Destroying an object by pressing a key

Discussion in 'Scripting' started by busterlock, Feb 24, 2018.

  1. busterlock

    busterlock

    Joined:
    Sep 26, 2015
    Posts:
    58
    Hey, everyone!
    My problem is very simple: I want for the user to delete a certain object he collides with.
    The thing is: Input.GetKey (or its variations) work properly only in Update(), while Destroy(other.gameObject) in this case works properly only in OnTriggerEnter (or its variations).

    Here is how I tried to make it work:

    Code (CSharp):
    1.  void Update()
    2.     {
    3.         if (GameController.geophoneCount < 3 && (Input.GetKeyDown(KeyCode.G)))  
    4.         {
    5.             wasDestroy = true;
    6.         }
    7.     }
    8.  
    9. void OnTriggerEnter(Collider other)
    10.     {
    11.        if (wasDestroy)
    12.         {
    13.             Destroy(other.gameObject);
    14.         }
    15.  
    16.     }
    The other strategy I thought was simply creating a Public GameObject in the script and destroying it, which would solve this specific problem, since I only want to destroy the one object, but then, what would happen if I wanted to destroy a thousand different ones?

    Is there any way to do it? Thanks.
     
    Last edited: Feb 24, 2018
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Let's say if only your player can collide with this game object, it's not very complicated. You can set a bool on the script when the player enters the trigger, and set it false upon exit. Now, if that bool is true and the key is down, you can destroy the game object.
    Such a script would be on the object you wish to destroy.

    I hope that helps :)
     
    busterlock likes this.
  3. busterlock

    busterlock

    Joined:
    Sep 26, 2015
    Posts:
    58
    You mean by OnTriggerEnter and OnTriggerExit, I did try that one of the times but there was a problem with it.
    I'll try again with a different logic and see if maybe it works.
    In case it does I'll just post the script in here as an answer.
    Thanks for the suggestion, man.