I want to make a script that if a collider with a tag (Example “killer”) it will destroy another gameobject with a Tag called (Example “prey”). How would I do this? Any help would be great! ![]()
Destroy object tagged “prey” when object tagged “killer” collides with it? You could use OnCollisionEnter, but only if the killer is a rigidbody (killer script):
function OnCollisionEnter(col: Collision){
if (col.gameObject.CompareTag("prey")){
Destroy(col.gameObject);
}
}
If killer is a CharacterController, you must use OnControllerColliderHit instead (killer script):
function OnControllerColliderHit(hit: ControllerColliderHit){
if (hit.gameObject.CompareTag("prey")){
Destroy(hit.gameObject);
}
}
Notice that only the tag “prey” is verified: usually the script with such code is attached only to a killer object, thus it’s not necessary to check its tag. But if this script may be attached to other objects that don’t have the tag “killer”, just include it in the if statement like below:
function OnControllerColliderHit(hit: ControllerColliderHit){
if (this.CompareTag("killer") && hit.gameObject.CompareTag("prey")){
Destroy(hit.gameObject);
}
}
The easiest way is to check the box in the collider of the gameobject with the tag “killer” for “is trigger”, then make a script, lets say it will be name CheckCollision and it wil be something like this:
using UnityEngine;
using System.Collections;
public class CheckCollision : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void OnTriggerEnter(Collider other)
{
//If the one colliding have the tag prey it
//will get destroyed
if(other.tag == "prey")
{
Destroy(other.gameObject);
}
}
}
Thats the code in C#
You should add this script to the gameobject with the tag “killer” and ofc, don’t forget to put them the right tag
hope it helps you!