How to delete the bullet and still shoot?

Viewed 31

I'm following a code monkey tutoreal on making a third person game. I tried to copy his code but when he deletes the bullet on impact he can shoot again but when I do it, it does not work.

Bullet code:

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

public class BulletProjectile : MonoBehaviour
{
    private Rigidbody bulletRigidbody;

    [SerializeField] private GameObject playerArmature;
    [SerializeField] private Transform vfxHitEnemy;
    [SerializeField] private Transform vfxMissEnemy;

    private void Awake()
    {
        bulletRigidbody = GetComponent<Rigidbody>();
    }

    private void Start()
    {
        float speed = 20f;
        bulletRigidbody.velocity = transform.forward * speed;
    }

    public void OnTriggerEnter(Collider other)
    {
        if (other.GetComponent<targetScript>() != null)
        {
            //hit target
            Instantiate(vfxHitEnemy, transform.position, Quaternion.identity);
        }
        else
        {
            Instantiate(vfxMissEnemy, transform.position, Quaternion.identity);
        }
        Destroy(gameObject);
    }
}

shooting code:

if (starterAssetsInputs.shoot)
    {
        Vector3 aimDir = (mouseWorldPosition - bulletSpawn.position).normalized;
        Instantiate(pfBullletProjectile, bulletSpawn.position, Quaternion.LookRotation(aimDir, Vector3.up));
        starterAssetsInputs.shoot = false;
    }
1 Answers

When the bullet is deleted, it won't exist anymore in your game so there won't be anything to shoot anymore.

To fix this you should make your bullet as a prefab, to do this you can just drag your bullet object to the assets folder and maybe make a special folder for those kind of objects. Then instead of instantiating the bullet that is already in your scene you need to spawn the prefab, then when the bullet is deleted the prefab will still exist and you will be able to spawn it again.

Related