Reference replaces itself with Missing when destroyed, but not consistently
Hello, I'm working on a bullet that is given a target and follows that target until either it hits the target, or the target is destroyed. The issue I'm running into is very rarely, for some reason, the target reference which is the transform of the target gameobject gets replaced with Missing (transform), and the bullet will stop moving and remain in the scene indefinitely.
I'm already checking if the target is null in my code but it doesn't seem to catch this. Here's the snippit of code that handles the movement of the bullet.
This happens in maybe one in every 500 to 1000 instantiations and I'm sure has something to do with the timing of when this bullet is created and the target is destroyed.
How do I check if the target is replaced with missing reliably?
private void Update()
{
pos = transform.position;
if(target != null)
{
tPos = target.position;
dir = tPos - transform.position;
}
if (Vector3.Distance(tPos, transform.position) >= speed*Time.deltaTime)
{
transform.Translate(dir.normalized * speed * Time.deltaTime, Space.World);
}
else
{
if (target == null)
{
die();
}
}
}
And this is what the script shows while the bug is presenting itself.
Your answer

Follow this Question
Related Questions
What is wrong with my code? C# beginner 1 Answer
Best way to learn how to utilize the Unity API? 2 Answers
Accessing Variables inside classes inside other classes? 1 Answer
Raycast shotgun help! 2 Answers