NullReferenceExeption on Instantiate Enemy

Im having a problem NullReferenceException in unity
When I do instantiate first the enemy, it usually occurs without the NullReferenceException.
Then when I do the second time, the NullReferenceException enemy appears and stops following the player and stands without moving
wanted help for it;
Script Link : Here

CORRECTED : and second times are is when I use instantiate once again*

I haven’t looked closley, but what sticks out is your use of DestroyImmediate. From the Docs:

Destroys the object obj immediately. It is strongly recommended to use Destroy instead.
This function should only be used when writing editor code since the delayed destruction will never be invoked in edit mode. In game code it is recommended to use Object.Destroy instead. Destroy is always delayed (but executed within the same frame) Use this function with care since it can destroy assets permanently!

If I had to take a shot in the dark i’m guessing your game object is being destroyed before Unity actually gets around to cleaning up your script. Thus your accessing a null object.

If you are having problem at this line var Direcao: Vector3 = (curTarget.transform.position - transform.position).normalized;

Then only reason could be that you are somehow destroying curTarget before this method executed fully.

And this “Somehow” could be DestroyImmediate.

Try Destroy instead of that.

There is more information regarding why you should almost never use DestroyImmediate in game. Unity - Scripting API: Object.DestroyImmediate

  • It could be good practice if you ahve checked if the target is not null before assigning it to curTarget

like by adding following line to the beginnign of the followway script if(!target) return;

thank’s :smiley: