- Home /
Game crash after trying to destroy an object?
Basically, I'm shooting a bullet out of character and after a certain amount of time the game just crashes.
generally crash's when I try to shoot again.
With this error
using UnityEngine; using System.Collections;
public class DestroyByTime : MonoBehaviour
{
public float lifetime;
void Awake()
{
Destroy(gameObject, lifetime);
}
}
Here the code for the bullets
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class shootsomething : $$anonymous$$onoBehaviour
{
public GameObject projectile;
public Vector2 velocity;
bool canShoot = true;
public Vector2 offset = new Vector2(0.4f, 0.1f);
public float cooldown = 1f;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.T) && canShoot)
{
GameObject go = (GameObject)Instantiate(projectile, (Vector2)transform.position + offset * transform.localScale.x, Quaternion.identity);
go.GetComponent<Rigidbody2D>().velocity = new Vector2(velocity.x * transform.localScale.x, velocity.y);
StartCoroutine(CanShoot());
}
}
IEnumerator CanShoot()
{
canShoot = false;
yield return new WaitForSeconds(cooldown);
canShoot = true;
}
}
is the GameObject projectile on the scene? Because it should not.
$$anonymous$$ake it a prefab. Assigned the prefab to the shootsomething.
Answer by Larry-Dietz · Dec 08, 2017 at 11:44 PM
Are you instantiating another bullet object each time you shoot? The error leads me to believe you are not. It looks like you are firing the bullet object you have, then destroying it, then when you try to shoot again, you are referencing the same bullet object you destroyed earlier.
-Larry