Search code examples
c#unity-game-enginepoolparticle-system

Understanding Unity's GameObject.Find(), GetComponent() and objects recycling


New to unity.

So I created a simple a simple muzzle flash particle animation that is supposed to be displayed on enemies gun when the player gets close to him, simulating a shot without the actual bullet. However I get a null reference exception in this part muzzleFlash.Play(); I believe it's because I am not actually getting the muzzle flash component in the start function with the code I have, actually I know that is it after going to in to debug mode I found out. I am having a really hard time figuring out how to access that component. Below is my code and I'm also posting a picture of my hierarchy. Thanks in advance.

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

public class StaticShootingEnemy : MonoBehaviour
{

    [SerializeField] private float _range = 12f;
    private Transform _player;

    private bool _alive;
    private float _distance;
    private ParticleSystem muzzleFlash;

    // Use this for initialization
    void Start()
    {
        _player = GameObject.Find("Player").transform;
        _alive = true;
        muzzleFlash = (ParticleSystem)this.gameObject.GetComponent("muzzleFLash");

    }

    // Update is called once per frame
    void Update()
    {
        _distance = Vector3.Distance(this.transform.position, _player.transform.position);
        if (_alive && _distance < _range)
            AttackPlayer();
    }


    private void AttackPlayer()
    {
        //Turning enemy to look at player
        transform.LookAt(_player);
        Ray ray = new Ray(transform.position, transform.forward);
        RaycastHit hit;
        if (Physics.SphereCast(ray, 0.75f, out hit))
        {
            //TODO: Fix enemy shooting fast when gettting close to him.
            GameObject hitObject = hit.transform.gameObject;
            if (hitObject.GetComponent<PlayerController>())
            {
                muzzleFlash.Play();
                Debug.Log("Player Hit!");
            }
            else
                muzzleFlash.Stop();
        }
    }

    public void SetAlive(bool alive)
    {
        _alive = alive;
    }

}

Hierarchy


Solution

  • You probably have an object "muzzleFlash" as child to object your script attached to. So, in this case you'd better have a reference to your ParticleSystem object that is called muzzleFlash.

    [SerializeField] private ParticleSystem muzzleFlash; // drag and drop your ParticleSystem muzzleFlash in inspector
    

    or at least you could find that muzzleFlash like this

    GameObject muzzleFlashObj = GameObject.Find("muzzleFlash"); ParticleSystem muzzleFlash = muzzleFlashObj.GetComponent<ParticleSystem>();

    In your case it's null because there is probably no component that is called MuzzleFlash on that object. The component you want to get is ParticleSystem.