N
N
NickNovicov2019-12-27 20:19:39
C++ / C#
NickNovicov, 2019-12-27 20:19:39

How to make bullet destruction on collision in Unity?

Good evening! Tell me where in the bullet code:

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


public class Bullet : MonoBehaviour
{

    public float speed = 100f;
    public Rigidbody2D rb;
    public GameObject bullet;
    // Start is called before the first frame update
    void Start()
    {     
        rb.velocity = transform.right*speed;
    }
    void OnTriggerEnter2D(Collider2D collider)
    {
        if(collider.gameObject.name != "Player")
        {
            Destroy(gameObject);
        }
    }

Something done wrong? When starting the game, it gives an error:
The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
In the lessons on the Internet, the same code.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
Homo Ludens, 2019-12-27
@HLudens

In order to avoid such glitches, it is necessary not to destroy the object, but to mark it as destroyed.
Well, then, after working out all the collisions, either destroy it or put it in the pool for reuse.

X
xmoonlight, 2019-12-28
@xmoonlight

1. Try to check the existence of an object before accessing its property:

if(gameObject && collider.gameObject.name != "Player")
        {
            Destroy(gameObject);
        }

2. If a shot is fired at the moment of collision of a bullet, then the object of the bullet is not destroyed, but placed in front of the barrel - only the coordinates change.
As it were, a chain conveyor is formed, which can greatly reduce the client's load when quickly creating and deleting objects.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question