- Home /
Question by
richardzzzarnold · Jan 23, 2019 at 09:21 AM ·
liststargetting
Targeting system error on destroyed target
I have a targeting system that selects the closest target from a list , like so:
using System.Linq;
if (Targets.Count>0){
selectedTarget = Targets.OrderBy(t=>(t.position - transform.position).sqrMagnitude)
.FirstOrDefault();}
It works great but it has started to give me the following error whenever i destroy a target and I can't work out why.
MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it.Your script should either check if it is null or you should not destroy the object.
Comment
Are you removing the object from the list before destroying it? test that.
Answer by tormentoarmagedoom · Jan 23, 2019 at 09:48 AM
Good day.
This is because the code is trying to read a variable of the destroyed object.
You need to remove that element from the list when you destroy it, so the code do not try to read that variable (that is null)
Bye!