- Home /
cloned bullet will not destroy on collision
hey, so when i try and use the code below to destroy my cloned bullet it doesnt destroy, it doesnt even fire the onCollisionEnter event so i am very confused. the bullet has a collider and a rigidbody so i am very confused. any help is appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shootScript : MonoBehaviour
{
public Rigidbody projectile;
public Transform barrelEnd;
// shoot the gun *bang*
void Update()
{
if (Input.GetMouseButtonDown(0)) {
projectile = Instantiate(projectile, barrelEnd.position, barrelEnd.rotation);
projectile.velocity = transform.TransformDirection(-30, 0, 0);
Destroy(projectile.gameObject, 10);
}
}
// destroy the bullet on enemy impact
private void OnCollisionEnter(Collision collision)
{
Debug.Log("test");
if (collision.gameObject.tag == "enemy") {
Destroy(gameObject);
}
}
}
Answer by Captain_Pineapple · Jul 17, 2021 at 02:17 PM
The OnCollisionEnter function will be triggered on the GameObject that actually collides with something. So your "bullet" gameobject needs a script with said OnCollisionEnter function. Then this will work as intended. Currently you basically listen for collisions of the gameobject that this "shootScript" is on.
Your answer
Follow this Question
Related Questions
Any collision with my cloned objects only affects the last clone created 1 Answer
clone functions 2 Answers
Give Clone Rotation from collided Object 1 Answer
Multiple colliders on one object? Or changing variables on a specific clone. 1 Answer
OnCollisionEnter not called when colliding with clone 0 Answers