- Home /
Other
How do I delete a bullet clone when it touches a game object or wall?
I'm still learning Unity but I'm not sure how to delete a bullet clone when it touches a game object. I had this problem where I would put in Destroy(gameObject); when it collides with something, but when I test it, it has an error where it deletes the bullet and not the clones. How can I make it so it only deletes the clones when the clones collides with a wall or enemy?
could you please share some code. I suspect that you're deleting reverence to prefab.
public class delete : MonoBehaviour {
void OnCollisionEnter2D(Collision2D collision)
{
Destroy(gameObject);
}
}
This is the code for deleting the bullet. There is a separate script for shooting the bullet if it's needed.
Answer by Woxell · Mar 06, 2021 at 11:35 PM
gameObject refers to the object that script is attached to. Make sure you use that function in right script. Or you can use;
void OnTriggerEnter(Collider collider){
Destroy(collider.gameObject) //the object that collided with your character.
}
Answer by Lifes_great · Mar 06, 2021 at 11:54 PM
When you mean clones are u meaning Prefabs? if so please give me both scripts you have written
Answer by Silver195 · Mar 07, 2021 at 12:04 AM
This is the code I used to make the bullet shoot. (got it from a Brackeys video)
public Transform firePoint; public GameObject bulletPrefab;
public float bulletForce = 20f;
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.right * bulletForce, ForceMode2D.Impulse);
}
}
@Silver195 I'm a bit puzzled on why u want to delete the clones as well as the bullet, is there any reasoning for that?
I wouldn't have a problem with the bullet clones not deleting but I fear that it might lag a lot because of the amount of bullets and having them continuously fly forward. Do you know if the bullets not deleting will cause any lag? If they really don't cause lag then I'm ok with it but I'm not sure.
Nah they wont cause lag. unless u are making a hyper Realistic 2D game but probably best to delete them anyway
Follow this Question
Related Questions
cant destroy other object 1 Answer
Deleting Bullets after a few seconds 2 Answers
how to have bullets produce particles? 2 Answers
RayCast Shooting And Errors 1 Answer