ONTRIGGER + COLLISION + KEY TO DESTROY

(OnTriggerEnter when collision) and Getkey to destroy instanly the object that collide

HELP ME :slight_smile:
IM NEW

IN C# LANGUAGE ONLY

2 Answers

2

Ok you thing 1 colliding with thing 2.

In code for thing being destroyed :

col is coding for whatever its colliding with right now! Just change A to whatever key on your keyboard you wanna press. This will destroy the object you attach this code to.

void OnTriggerEnter(Collider col)
if (Input.GetKey (KeyCode.A)){
        if(col.gameObject.name == "game object's exact name")
        {
            Destroy(col.gameObject);
        }}

This is for colliding with a lot of things, might wanna use this for future then just code for colliding with things that have tags.

void OnTriggerEnter(Collider other)
	{ if (other.CompareTag ("tag exact name")) {
			if (Input.GetKey (KeyCode.A)) {
                        Destroy(other.gameObject);

}
		}

Small note if wanna script this on your main object like a player then destroy the OTHER object you need to do something like

public gameObject thingbeingdestroyed;

void Start(){
thingbeingdestoryed = gameObject.Find("objects exact name").GetComponent<RectTransform>();
}

Then when destroying do

{
               Destroy(thingbeingdestroyed);
}

Think that should work, just thought that up.

thank you and realy appreciate,, can you give me the code from begining (full).. im afraid there is a lot of error..

–

Just use this script on the item that will will destroy the other. This script will only work for something small unless you want to destory any future gameObjects that collide with this thing. using UnityEngine; using System.Collections; public class ScriptName: MonoBehaviour { void OnTriggerEnter(Collider other) { if (Input.GetKey (KeyCode.A)){ Destroy(other.gameObject); }} }

–

Input should be called in Update() or Corutines only. See doc :
http://docs.unity3d.com/ScriptReference/Input.html

on OnTrigger / OnCollision functions. That won’t work or if it’s it’ll be very buggy…

using UnityEngine;

public class ScriptName : MonoBehaviour
{
    GameObject objToDestroy;
    bool canDestroy = false;

    void OnTriggerEnter(Collider other)
    {
        objToDestroy = other.gameObject;
        canDestroy = true;
    }
    void Update() {
        if (Input.GetKey(KeyCode.A) && canDestroy)
        {
            Destroy(objToDestroy);
            canDestroy = false;
        }
    }
}

thank you..its work

–