Home > Mobile >  Unity Bullets stop working when using destroy gameobject
Unity Bullets stop working when using destroy gameobject

Time:11-12

I have been doing a tutorial for network games using Unity but I am having trouble with the bullet, whenever I include the private void OnCollision thing, the bullet will not initialise if I press space but if I remove it the bullets will be there but I am trying to avoid the arrays of the bullet (clone) when shooting so I want to destroy the bullet. I used the code

//private void OnCollisionEnter(Collision collision)
//{
//    Destroy(gameObject);
//}

In my bullet script that I have created, I have had to comment out the lines as whenever I use this and play the game the space button which shoots the bullets don't work at all.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour
{
Rigidbody rigidbody;
// Start is called before the first frame update
void Awake()
{
    rigidbody = GetComponent<Rigidbody>();
}

public void InitializeBullet(Vector3 originalDirection)
{
    transform.forward = originalDirection;
    rigidbody.velocity = transform.forward * 18f; 
}

//private void OnCollisionEnter(Collision collision)
//{
//    Destroy(gameObject);
//}

}

Bullet prefab

CodePudding user response:

This is probably happening due to OnCollisionEnter function gets triggered when the gameobject collides with something. When you instantiate the bullet it probably collides with the player character itself as that also has a collider, thus instantly destroying itself.

A simple solution would be to check the tag of the collided gameobject to make sure that the bullet collided with something that we want it to. So after setting the enemy prefab to have it's own tag your collision code would look like this:

private void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.tag == "Enemy") //I choosed enemy as the custom tag
    {
        Destroy(gameObject);
    }
}

CodePudding user response:

I figured out what went wrong as @66Gramms talked about the bullet colliding with the player character I had another game object called bullet position where I was suppose to put it in front of the player character but instead I didn't do that, the player and bullet were together colliding smh. So the code I used

private void OnCollisionEnter(Collision collision)
{
    Destroy(gameObject);
}

Actually works

  • Related