Error: The variable deathFX of Enemy has not been assigned

My code is exactly as Bens in the enemy script but as soon as I hit an enemy the game pauses and throws an Unassigned Reference Exception: The variable deathFX of enemy has not been assigned. It is in the inspector, it is applied to the prefab, it is in all the enemies in the scene. I have removed the enemies and added new ones and I get the same error. I have no idea what is going on…any help would be greatly appreciated.



image

Hi Tim

It’s a little bit difficult to tell from the chopped up screenshots, note, with code you can just copy/paste it into your posts and apply code formatting.

If you would like to zip up your project files and share them I will happily take a look for you and see if there is anything I can spot.

The forum will allow uploads of up to 10MB, if your project files (zipped) are larger than that you would need to use a service such as Google Drive or Dropbox, and then share the URL.


See also;

The only thing I can think of to ask at the moment given the available data: in the upper screen shot we see that you have something assigned to the script in the inspector… what is selected? Is it a prefab? If so, I think that’s the problem, perhaps? If, instead, the item shown has been selected from the hierarchy, and is in the scene, then… is the prefab you’ve dropped into DeathFX really what you think it is?

1 Like

Sorry Just able to get back to this.
Here is the code but unfortunately the project is almost 1gb for some reason…actually I am pretty sure of the reason and I have to do some cleaning out of assets. I cleaned out the comments to make it easier to read. Other than the code I redid the steps in the lecture and get the same result

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

public class enemy : MonoBehaviour {

    [SerializeField] GameObject deathFX;
    [SerializeField] Transform parent;

	void Start () {

        Collider boxCollider = gameObject.AddComponent<BoxCollider>();
        boxCollider.isTrigger = false;

    }


    private void OnParticleCollision(GameObject other)
    {
        
        GameObject fx = Instantiate(deathFX, transform.position, Quaternion.identity);
        fx.transform.parent = parent;

        Destroy(obj: gameObject);
    }
}

Thank you for replying - I went back and re-watched the lecture to see if I had done it incorrectly. According to the lesson you need to make the Enemy Death FX a prefab and then attach it to the script in the inspector. That way it instantiates the death fx just before it blows up. I have done this twice now through the lecture and get the same result so I am unsure how to continue at this point. I have attached a screenshot from the lesson where it shows Ben attaching the prefab to the script. If that wasn’t what you meant I apologize as that is how I read your answer.

In the Editor image above, it shows that the selection in the hierarchy is the 8 enemy ships. We can see all 8 ships have the Enemy script component. We can see that the prefab, “EnemyDeathFX” has been assigned to the 8 enemy ships for the “DeathFX” reference.

Assuming the “EnemyDeathFX” prefab is setup correctly, this looks good; but the picture is marked as “Ben’s Screen” (presumably a screen cap from the class?) If so, as indicated, it seems to be what you’d be looking for… Select your enemy(s) in the hierarchy, see that they have the Enemy script component, and assign the EnemyDeathFX prefab to the DeathFX prefab reference for each enemy in the scene.

Part of what I was trying to say in my first post is that the way the original image is cropped, I have no idea what the selection is in the hierarchy, if anything. On second look, I see the orange highlight on the crab, which I think means the image does indeed show an object selected from the hierarchy (vs. the inspector information being for a selected prefab, which was my concern).

So, assuming that part is not where the problem lies, there’s still the second part of my original post: Maybe your EnemyDeathFX prefab isn’t finished? i.e. maybe you set it up while in “Play” mode, and lost the changes when you stopped? What is the state of your prefab?

Just to add, the script above looks ok, so its likely to be the configuration in the editor as Jack is suggesting above.

Thanks for trying to apply the code formatting, as a heads-up, its three of there ` characters, as opposed to three of these ', I’ve updated the post for you :slight_smile:

Also, minor note, this line;

Destroy(obj: gameObject);

You don’t need to try and cast the object to be destroyed first, a GameObject derives from Object (eventually), so you can just use;

Destroy(gameObject);

If you are still unable to spot anything via the Inspector after following Jack’s reply, zip up the project and share it and we’ll take a look. The size doesn’t really make a lot of difference for myself, although if the zipped files are larger than 10MB you will need to use a service like Google Drive or Dropbox.

If you make a separate copy of the project first you can always delete the /library folder first too, this will help reduce the size, but again, not entirely necessary from my perspective.

It’s been a crazy week so I apologize for my late reply. Thank you for fixing the post for me. I couldn’t tell what character that actually was but I think I’ve got it now. Below is a link to the zipped project on google drive. I tried to clean out most of the assets I am not using but there are a few hanging around. The skybox being the big one but I am using it so I can’t remove it. As for the line in code -

Destroy(obj: gameObject); 

Visual Studio wouldn’t shut up about it being wrong and to get rid of the squgglies I caved and let it change it to whatever it thought it should change it to.

Speaking of which I did see that my one function was private so I changed that and things were looking good for a minute but then the same result occurred when one of the bullets hit the enemy crab(s). I punted all the crabs out of my scene, saved it, shut Unity down, restarted and reimported my crab from the asset pack. I went back and retraced all the steps and still the same result. As for knowing whether the asset is correct or not I don’t know enough to tell by looking at it.

Any advice you can give would be welcome.

Thanks in advance.

Link to project as of 10-08-2018
https://drive.google.com/open?id=1sjQ9HXjGvgXtL6buBmq6-XI4vUS54sfs

Hi Tim,

I’ve just downloaded your project and am going to take a quick look now.

Just to be clear on what I’m looking for, as it’s been a little while since the conversation was going back and forth;

  • you are experiencing an issue with the DeathFX GameObject
  • you are experiencing an issue with the Destroy method in code

Are those your two main issues?


Updated Tue Oct 09 2018 17:38

Let’s take a journey together… :slight_smile:

On opening the project I was taken to a new/empty scene. I loaded Level1.

All of the scripts components attached to the Jet GameObject are provided warnings;

image

The console contained a number of messages, warnings and errors. I assumed some may be from opening the project as I am using a slightly newer version of Unity than the one your created your project in. I clicked on Clear and all but two of the errors disappeared, the remaining two errors were;

Opening up the BetterWaypointFoller.cs script I saw that the UnityStandardAssets.Utility directive at the top was erroring and also on line 19, it didn’t know what type WayPointCircuit was. I checked your project to see if you had the Standard Assets, you do have a folder for the, but the Utility folder is empty.

I copied across (from another project) the WayPointCircuit.cs script file.

The code recompiled within Unity and both error messages went away. In addition, the warnings about your own scripts also disappeared and, with the code now compiled, your exposed fields were now visible within the Inspector.

Not sure if the Utility folder was something you accidentally cleared down whilst trying to provide me with the zip file, or, if you are missing these files in your local working copy, but it would seem that your BetterWaypointFollower.cs script has a reliance on an existing asset from Standard Assets - so you can’t just delete that :slight_smile:

Next, looking at your Collision Handler component on the Jet GameObject, I could see this;

image

So, no DeathFX are currently being referenced.

Looking in your project I was unable to see a prefab that was named PlayerDeathFX or similar, so I dragged your EnemyDeathFX prefab into the scene to check that it was ok and going to do something when played. It did. I deleted it again from the scene.

I dragged the prefab EnemyDeathFX into the Player Death FX field on your Collision Handler script component. I was aware that this GameObject is not active by default, but your code within the OnTriggerEnter method sets it to active, so I figured this would be sufficient.

I ran your game.

Your ship appears and is shooting, some enemies are visible in the distance, the ship doesn’t move and the console is riddled full of warnings and errors again, focusing mainly around this BetterWaypointFollower.cs script.

image

Before I go further here I just want to mention that you actually do rip out the WaypointTracker functionality later in this section and replace it all with Unity’s Timeline functionality.

Moving on…

The Circuit GameObject was missing the WaypointCircuit.cs script which I had to add back to the project, I re-referenced that script component, and re-set all of the child waypoint GameObjects within this component;

I ran your game again. This time the player ship moved, fired and things looked more as you would expect.

When the player ship collided however the level was reloaded, which made it very difficult to determine if the EnemyDeathFX I had set did anything. I commented out this line of code in the OnTriggerEnter method of PlayerCollision.cs;

Invoke("ReloadLevel", levelLoadDelay);

At the point of collision I was then presented with the following message, warning and error;

image

I’ll skip over the BoxCollider size issue for the moment and come back to that, but looking at the two errors, which were what you mentioned in your original topic, these were traced back to the Enemy’s in your scene. You have added the Enemy.cs script component to the parent GameObject but also to each child GameObject. The reason for the error is because you have then only made the reference to the EnemyDeathFX on the parent GameObject, example;

Parent GameObject

000 Child GameObject

Box01 Child GameObject

As these are prefab’d, the easiest way to resolve this is to correct the issue on the prefab. Select the Prefabs folder under _Assets, select and expand bdl_byx;

image

  • Select it’s child 000 GameObject and remove the Enemy.cs script component
  • Select it’s child Box01 GameObject and remove the Enemy.cs script component

This will leave the Enemy.cs script component only on the parent GameObject for this prefab.

The most likely way that you would have managed to have added these by accident would have been if, in the Hierarchy you had the GameObject expanded, and then selected it in such a way that its children were highlighted too, then, adding the Enemy.cs script component would have been applied to all of the selected GameObjects.

Run your eyes across the instances in the scene of this prefab and you’ll now see that they no longer have the extra script components.

Run the game.

Yay, no errors. Nothing particularly exciting when a collision is made either, for the player at least.

So, back to the OnTriggerEnter method in PlayerCollision.cs, I added this line of code;

GameObject fx = Instantiate(playerDeathFX, transform.position, Quaternion.identity);

Which gives us this, just as an example, this isn’t inline with the course content;

    private void OnTriggerEnter(Collider other)
    {
        //print("Player triggered something");
        StartDeathSequence();
        playerDeathFX.SetActive(true);

        GameObject fx = Instantiate(playerDeathFX, transform.position, Quaternion.identity);

        // Invoke("ReloadLevel", levelLoadDelay);
    }

Run the game again, don’t move the ship, just let is hit something on it’s own, and you’ll see the particle effect appear (same as the enemy being destroyed) and this GameObject instantiated in the Hierarcy;

image

Note, I didn’t bother parenting it as it was simply to demonstrate that the Player Death FX works.

Back to the Box Collider issue, this doesn’t seem to be a problem now, and the warning doesn’t seem to appear again at this stage.

And finally… the Destroy syntax…

If I open Enemy.cs I see the following method;

void OnParticleCollision(GameObject other)
{
    GameObject fx = Instantiate(enemyDeathFX, transform.position, Quaternion.identity);
    fx.transform.parent = parent;
    print("Particles collided with enemy" + gameObject.name);
    Destroy(obj: gameObject);
    Debug.Log("enemy destroyed");
}

I changed;

Destroy(obj: gameObject);

to;

Destroy(gameObject);

No issues were present, no warnings, no errors, all good. It might be that Visual Studio was being a bit specific because it was unable to build your solution due to the other errors/issues above.

Don’t forget, if you want the scene to be reloaded when the player crashes, edit the OnTriggerEnter method again and uncomment the line we commented out above.

You should probably try to own particle effects now for the Player Death FX too, now that you know the rest is fixed.

This reply is lengthy but gives you step by step instructions to resolve the issue as long as your project is the same version as that which you provided me with. Bear in mind my comment above about me using the enemy death fx just as a test and the code I added to OnTriggerEnter in PlayerCollision.cs is not inline with the course content, just for diagnosing your issues and making it work for a demonstration.

Hope this helps :slight_smile:

1 Like

Rob,
I can’t thank you enough and I can’t apologize enough! When I was cleaning things out I broke nearly everything which you then had to sift through. :persevere: That was not my intention and again I apologize that you had to wade through the mess I made. I have it all fixed based on your step by step guide and everything seems to be working. I must have, as you suggested, highlighted the enemies in the hierarchy while expanded. I honestly didn’t even think about those and I must have applied it the same way back to the main prefab as I kept redoing it and getting the same errors.

Thank you once again for all your patience especially after I botched up the cleaning part royally. I can finally move on from this part after I replace some of my crabs.
:grin:

1 Like

Flag this one for your “annual review”, Rob. :slight_smile:

You definitely go the extra mile to help around here. Kudos to you!

1 Like

Hey Tim,

I can’t thank you enough

You are very welcome Tim :slight_smile:

I can’t apologize enough! When I was cleaning things out I broke nearly everything which you then had to sift through. That was not my intention and again I apologize that you had to wade through the mess I made

No problem at all, I wasn’t sure at first whether it was perhaps broken because you’d got yourself into a bit of a situation with it, or, if it was just through clearing stuff down to reduce the zip size - e.g. trying to help. It didn’t take long before I assumed the latter, I’m fairly sure you’re description of the problem you were experiencing would have been different otherwise. It’s all good, keeps me busy and out of trouble - no need to apologise :slight_smile:

I have it all fixed based on your step by step guide and everything seems to be working.

Fantastic, I’m glad that the information I posted help.

I must have, as you suggested, highlighted the enemies in the hierarchy while expanded.

I think it’s probably the most likely way that you could have got the script on the child GameObjects, it’s not something I could imagine you doing deliberately, and if you had, you’d probably have dragged the prefab to the field on all of them too, as you’d have been aware of the script being there. If there is anything to take away from your experience I would suggest it’s that, so actually, you’re issue has turned out to be a learning tool - bonus! :slight_smile:

Thank you once again for all your patience especially after I botched up the cleaning part royally. I can finally move on from this part after I replace some of my crabs.

You’re very welcome Tim, I’m really pleased you can move forward again and happy to have been able to help.

All the best :slight_smile:

Hey Jack,

Thank you for the kind words Jack, appreciated.

I’m happy to help where I can and appreciation how frustrating and demoralising it can be when students get stuck and just need that little bit of extra help to get going again. It’s very rewarding to know that someone else’s day will be that little bit better/happier just because you’ve given them a little bit of your time. :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms