(OnTriggerEnter when collision) and Getkey to destroy instanly the object that collide
HELP ME
IM NEW
IN C# LANGUAGE ONLY
(OnTriggerEnter when collision) and Getkey to destroy instanly the object that collide
HELP ME
IM NEW
IN C# LANGUAGE ONLY
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.
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;
}
}
}