Shooting problem: "The object of type 'GameObject has been destroyed"

I have this code:

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

public class Bullet : MonoBehaviour
{
    public float speed;
    private Rigidbody2D m_rig;
    public Transform player_pos;


    // Start is called before the first frame update
    void Start()
    {
        m_rig = GetComponent<Rigidbody2D>();
        m_rig.AddForce(Vector2.right*speed, ForceMode2D.Impulse);
        Invoke("Destruir_", 2);
    }

    // Update is called once per frame
    void Update()
    {
        //Flip bullet

        if (player_pos.position.x > this.transform.position.x)
        {
            speed *= -1;
        }
        else
        {
            speed *= -1;
        }
    }

    void Destruir_()
    {
        Destroy(this.gameObject);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Destruir_();
       
    }

 

}

And when i try to play the game i have an error that says: “MissingReferenceException: The object of type 'GameObject has been destroyed but you are still trying to access it.” And when i see the hierarchy the object of bullet has been destroyed but i don’t understand why doesn’t appear again the bullet. I’m new at coding, probably i missing something but i don’t know what.

Why are you invoking Destruir_ in your start routine?

I did this following a tutorial and he did it in that way. But are you saying i should put the invoke on the update maybe?

No, it is just an odd way to do things. You might try temporarily commenting it out and seeing if it is the cause of the issue though.

I was able to solve it this way:

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

public class Bullet : MonoBehaviour
{

public float bulletSpeed = 15f;
public Rigidbody2D rb;
public Transform player_pos;

void Start()
    {
        player_pos = GameObject.Find("Player").transform;
    }

private void FixedUpdate()
    {
        if (player_pos.position.x > this.transform.position.x)
        {
            rb.velocity = transform.right * bulletSpeed;
        } else
        {
            rb.velocity = transform.right * -bulletSpeed;
        }
    }
     
    private void OnCollisionEnter2D(Collision2D collision)
    {
        Destroy(gameObject);
      
    }

}
1 Like