I’m following a tutorial and I’ve come across an error after the player destroys an enemy ship.
I added a new GameObject variable called enemy and I would only do what was in FixedUpdate if enemy wasn’t null to try and fix this. It worked but only if there was one enemy on screen. If there were multiple, and I killed one I still got the error in the console. Here is the code for that
public Boundary boundary;
public float dodge;
public float smoothing;
public float tilt;
public Vector2 startWait;
public Vector2 maneuverTime;
public Vector2 maneuverWait;
public GameObject enemy;
private float currentSpeed;
private float targetManeuver;
private static Rigidbody rb;
void Start ()
{
StartCoroutine (Evade ());
rb = GetComponent <Rigidbody> ();
currentSpeed = rb.velocity.z;
}
IEnumerator Evade ()
{
yield return new WaitForSeconds (Random.Range (startWait.x, startWait.y));
while (true)
{
targetManeuver = Random.Range (1, dodge) * -Mathf.Sign (transform.position.x);
yield return new WaitForSeconds (Random.Range (maneuverTime.x, maneuverTime.y));
targetManeuver = 0;
yield return new WaitForSeconds (Random.Range (maneuverWait.x, maneuverWait.y));
}
}
void FixedUpdate ()
{
if (enemy != null)
{
//I'm getting the error here
float newManeuver = Mathf.MoveTowards (rb.velocity.x, targetManeuver, Time.deltaTime * smoothing);
rb.velocity = new Vector3 (newManeuver, 0.0f, currentSpeed);
rb.position = new Vector3 (
Mathf.Clamp (rb.position.x, boundary.xMin, boundary.xMax),
0.0f,
Mathf.Clamp (rb.position.z, boundary.zMin, boundary.zMax)
);
rb.rotation = Quaternion.Euler (0.0f, 0.0f, rb.velocity.x * -tilt);
}
}
I don’t know what to do to fix this so any help is appreciated.
