Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

MissingReferenceException when using particle system

Discussion in 'Scripting' started by Varga87, Aug 5, 2020.

  1. Varga87

    Varga87

    Joined:
    Jun 3, 2019
    Posts:
    6
    I have two particle systems as death effect for my enemies. They are prefabs and have 'destroy' as stop action and i want them to instanciate every time an enemy die. This is the function called on death:
    Code (CSharp):
    1.     private void ExitExplodingState() {
    2.         aliveAnimator.SetBool("exploding", false);
    3.  
    4.         GameObject exp1 = Instantiate(deathParticles, alive.transform.position, deathParticles.transform.rotation);
    5.         GameObject exp2 = Instantiate(deathBloodParticles, alive.transform.position, deathBloodParticles.transform.rotation);
    6.  
    7.         exp1.transform.SetParent(null);
    8.         exp2.transform.SetParent(null);
    9.  
    10.         Destroy(gameObject);
    11.     }
    It works fine on the first enemy but then i get a MissingReferenceException on the next enemy that dies and everything gets messed up, enemys get stuck in weird states, particles appear on the wrong place, etc.

    Can anyone please help me with this?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    Some notes on how to fix a NullReferenceException error in Unity3D
    - also known as: Unassigned Reference Exception
    - also known as: Missing Reference Exception

    http://plbm.com/?p=221

    The basic steps outlined above are:
    - Identify what is null
    - Identify why it is null
    - Fix that.

    Expect to see this error a LOT. It's easily the most common thing to do when working. Learn how to fix it rapidly. It's easy. See the above link for more tips.
     
  3. Varga87

    Varga87

    Joined:
    Jun 3, 2019
    Posts:
    6
    Thanks, I managed to solve my issue!
     
    PraetorBlue and Kurt-Dekker like this.
  4. OrlovskyConsultingGbR

    OrlovskyConsultingGbR

    Joined:
    Mar 17, 2020
    Posts:
    63
    hi all!
    I can only add, that such thing can be avoided if you write test first, Unity have real good documentation about how to write tests.
    You can think this crazy to write test first even if there no code, well let me reassure you, by thinking about how to test stuff which is not exist you setting your programmers expectation from such point that all things happen as they suppose to happen, if you code hard to read , then you think twice and rewrite it make it smaller and test give you such freedom so that you can refactor your code whenever you wish , if all tests pass green you can deliver......