The object of type "gameobject" has been destroyed but you are still trying to access it

hello guys i got two problems with the script i made first its a gun shooting script and the problem is is that the bullets turn side ways when they are shot but the big problem is is that the gun only shoots like 5 times then i get this message "The object of type “gameobject” has been destroyed but you are still trying to access it " and its stops shooting does anyone know how to fix this

heres my script

using UnityEngine;
using System.Collections;

public class Shoot : MonoBehaviour {
	
	public GameObject bullet;
	public GameObject bulletHole;
	public float delayTime = 0.5f;
	private float counter = 0;
	
	void FixedUpdate ()    
	{
		if(Input.GetKeyDown(KeyCode.Mouse0) && Time.time >= counter)
		{
			Instantiate(bullet, transform.position, transform.rotation);
			audio.Play();
			counter = Time.time + delayTime;
			
			RaycastHit hit;
			Ray ray = new Ray(transform.position, transform.forward);
			if(Physics.Raycast(ray, out hit, 100f))
			{
				Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
			}
		}
	}
}

I suspect your problem has to do with a different script... the one that destroys your bullets when they collide with something. Show us that too, please?

Do you have an additional code where you destroy the bullet?, if this is the case, can you paste that code?

Also, it would be better to have both bullet and bulletHole referenced to prefabs, instead of a gameObject within the scene

3 Answers

3
  • You just instantiate… Not giving it a forward velocity? Then it could go sideways… most probably just fall down…
  • Where do you destroy your bullet?
  • The error message would also say which line (and file) the error happened, and that pretty much gives an idea on which “destroyed Object” you are trying to access…

I’d suggest not to post incomplete questions if you honestly want an answer.

I would suggest that your code for detecting if a bullet is out of bounds is destroying all bullets once the first goes out of bounds.

heres my second gun script i use to eject the bullets \

using UnityEngine;
using System.Collections;

public class MoveBullet : MonoBehaviour {

	public float speed = 1f;

	void Start ()	
 	{
		Destroy(gameObject, 5f); //Delete the bullet after 5 seconds
	}
	
	void Update ()	
 	{
		transform.Translate(0, 0, speed);
	}
}

Good start, now show us the complete error message including any line numbers it prints.,