- Home /
NullReferenceException after target is destroyed
After rayCast.collider.gameObject is destroyed I get the null reference exception, even if I set a break statement. Any Ideas?
This is the actual error: Movement+c__Iterator0.MoveNext() not set to an instance of an object
IEnumerator Rotation(RaycastHit rayCast)
{
if(rayCast.collider.gameObject == null)
{
yield break;
}
for (int count = 0; count < 50; count++)
{
//Here is the actual error
Vector3 dir = rayCast.collider.transform.position - transform.position;
Quaternion quaternion = Quaternion.LookRotation(dir);
Vector3 rotation = Quaternion.Slerp(transform.rotation, quaternion, Time.deltaTime * speed).eulerAngles;
transform.rotation = Quaternion.Euler(0f, rotation.y, 0f);
yield return new WaitForSeconds(0.01f);
}
}
treyh: added code formatting
Answer by TreyH · May 15, 2018 at 04:36 PM
This just looks like simple confusion on how the coroutine's yield instructions work. Those just put off execution until the yield instruction has been satisfied, so in this case it will resume your for
loop.
IEnumerator Rotation(RaycastHit rayCast)
{
for (int count = 0; count < 50; count++)
{
// I don't remember if collider and gameobject will both be null,
// probably? You can remove the 2nd check if collider itself will
// return null when the object is removed.
if(rayCast.collider == null || rayCast.collider.gameObject == null)
{
break;
}
//Here is the actual error
Vector3 dir = rayCast.collider.transform.position - transform.position;
Quaternion quaternion = Quaternion.LookRotation(dir);
Vector3 rotation = Quaternion.Slerp(transform.rotation, quaternion, Time.deltaTime * speed).eulerAngles;
transform.rotation = Quaternion.Euler(0f, rotation.y, 0f);
yield return new WaitForSeconds(0.01f);
}
}
Thank you very much! Checking for rayCast.collider ins$$anonymous$$d of rayCast.collider.gameObject fixed my issue!
Well, the if
statement is also now sitting inside of your for
loop, which will let it catch if the collider / gameobject are no longer available.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
NullReferenceException script problem? 0 Answers
[Solved] Actually totally explainable NRE with 2D array 0 Answers
Null Reference Exception: Object Reference, with base class? 1 Answer