stopping an error messages with no player active

this is something im having a little bit of trouble figuring out

but i have a small script of enemies attacking a player when they spawn on screen, they are attracted too it right away with

player = GameObject.Find("Player").transform.position;
difX = player.x - transform.position.x;
difY = player.y - transform.position.y;
playerDirection = newVector2(difX,difY);

so when they spawn they go right to the player. this is stored in UPDATE.
BUT. when the player dies, an error pops up
“NullReferenceException - Object reference not set too an object”

and i understand why, its because the player is no longer on screen. but have tried doing this to Awake() also Start(), which does work to some degree, it does take away the error message.
but, it only updates on the last position, so the enemy stays where the player was last. if i move the player, the enemy will not follow. only the newest spawned enemy will, until i then move the player again.
how can this be fixed?

thanks

What about checking if GameObject.Find(“Player”) returns null?

so that would be something like this?

if(GameObject.Find("Player") == null){
   return;
}

but did try and still the same.

thanks for your help as well.

hmmm. still not getting anything right now.

did try a return right at the end just to see, even though i knew it wouldn’t work.
just a bit stumped to be honest

actually fixed it. BOOSH

i put it in FixedUpdate. and it all works perfectly, no errors at all. plus it still keeps everything as it should

BOOM. now i can finish this project :wink:

thanks again

actually. nope, i was completely wrong.

whilst it stops it in UNITY. it crashes on a device. which makes sense.
so im still after a solution if anyone can help. would mean a lot

thanks

Transform player;

void Start(){
     player = GameObject.Find("Player").transform; // better ways to do this... but not the topic
}

void Update(){
//whatever you have
     if(player){ 
          difX = player.position.x - transform.position.x;
          difY = player.position.y - transform.position.y;
          playerDirection = newVector2(difX,difY);
     }
// whatever else
}

[edit]: copying code from above adds in garbage html links… edited to remove them…

oooh. wow. thank you very much.

ill have a look see in a minute and check it out.

again, thank you

checked and its all working fine.

thank you very much, the both of you. got some reading to do me thinks and bone up on UNITY more :wink:

again, thanks