Answer the question
In order to leave comments, you need to log in
Why is this error coming out (ParticleSystem was destroyed and you are accessing it)?
Mistake:
MissingReferenceException: The object of type 'ParticleSystem' 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.
UnityEngine.ParticleSystem.Play () (at C:/buildslave/unity/build/Runtime/ParticleSystem/ScriptBindings/ParticleSystem.bindings.cs:269)
Gun.Shoot () (at Assets/Gun.cs:40)
Gun.Update () (at Assets/Gun.cs:32)
MissingReferenceException: An object of type 'ParticleSystem' has been destroyed, but you are still trying to access it.
Your script must either check if it is null or you must not destroy the object.
UnityEngine.ParticleSystem.Play() (in C:/buildslave/unity/build/Runtime/ParticleSystem/ScriptBindings/ParticleSystem.bindings.cs: 269)
Gun.Shoot() (in Assets/Gun.cs: 40)
Gun.Update () (in Assets/Gun.cs: 32)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
public float damage = 21f;
public float fireRate = 1f;
public float range = 40f;
public float force = 40f;
public ParticleSystem muzzleFlash;
public Transform bulletSpawn;
public AudioClip shotSFX;
public AudioSource _audioSource;
private float nextFire = 0f;
public GameObject hitEffect;
public Camera _cam;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetButton("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + 1f / fireRate;
Shoot();
}
}
void Shoot()
{
_audioSource.PlayOneShot(shotSFX);
//Instantiate(muzzleFlash ,bulletSpawn.position,bulletSpawn.rotation);
muzzleFlash.Play();
RaycastHit hit;
if(Physics.Raycast(_cam.transform.position,_cam.transform.forward, out hit, range))
{
GameObject impact = Instantiate(hitEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impact, 2f);
if(hit.rigidbody !=null)
{
hit.rigidbody.AddForce(-hit.normal * force);
}
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question