Why am I getting a Null Reference Exception?
The scenario I have set up is a car is going down a highway with other cars. These cars a randomly generated with random speeds. I am attempting to use Raycast so that the path finding can be somewhat procedural. The problem I am running into is the Raycast will hit something then say that there is a null reference exception when I have tried to access the object. I am actually referencing another instance of the script.
What is primarily confusing me is when the Raycast hits something it should return an object. However, if it doesn't hit anything it shouldn't even activate the code.
As to where it is called in the script. It is being called in the fixedupdate function and I am calling it multiple times so that it will the ray will cast from the left and right edges and the center of the object. If I need to include more information, please let me know as this is my second time asking a question on these forms.
Location = transform.position;
for (int x = -1; x <= 1; x++)
{
Ray ray = new Ray(Location + new Vector3(x * extents.x, 0f, 0f), Vector3.back);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Motor Motorcade = hit.transform.gameObject.GetComponent<Motor>() as Motor;
bool OpposingChangingLane = Motorcade.ChangingLane;
float OpposingSpeed = Motorcade.Speed;
if (hit.distance < 5)
{
if ((Speed - OpposingSpeed) <= .75)
{
Speed = OpposingSpeed;
}
else if ((Speed - OpposingSpeed) > .75)
{
if (OpposingChangingLane == false)
{
ChangingLane = true;
}
else if (OpposingChangingLane == true)
{
Speed = OpposingSpeed - 1f;
}
}
}
else if (hit.distance >= 5)
{
Speed = OriginalSpeed;
}
}
}