Crash

Kissen

Member
Joined
Jun 20, 2019
Messages
13
Programming Experience
Beginner
My unity crashes when I run this code and the foodobject is outside of the searchscope of the "player".
The "player" should search for the closest foodobject and if there is none within its scope it should pick a random position and move towards it.

C#:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class move : MonoBehaviour
{
public float scope = 10;
public float speed = 1;
Vector2 randomPos;
bool Notarget = true;
bool canChoose = true;
// Update is called once per frame
void Update()
{
FindClosestConsumable();
}

void FindClosestConsumable()
{
float distance = Mathf.Infinity;
consumable closestConsumeable = null;
        consumable[] AllConsumables = GameObject.FindObjectsOfType<consumable>();
        foreach(consumable currentConsumable in AllConsumables)
{
float distanceToFood = (currentConsumable.transform.position - this.transform.position).sqrMagnitude;
if(distanceToFood < distance)
{
distance = distanceToFood;
closestConsumeable = currentConsumable;
}
}
Debug.DrawLine(this.transform.position, closestConsumeable.transform.position);

if(Mathf.Sqrt(Mathf.Pow((this.transform.position.x - closestConsumeable.transform.position.x),2) + Mathf.Pow(this.transform.position.y-closestConsumeable.transform.position.y,2)) < scope)
{
Notarget = false;
this.transform.position = Vector2.MoveTowards(this.transform.position, closestConsumeable.transform.position, speed*Time.deltaTime);
}
else
{
Notarget = true;
while (Notarget)
{
if (canChoose)
{
float Height = Random.Range(-4.5f, 4.5f);
float Width = Random.Range(-7f, 7f);
randomPos = new Vector2(Width, Height);
canChoose = false;
                }


this.transform.position = Vector2.MoveTowards(this.transform.position, randomPos, speed * Time.deltaTime);
}

}
}
}
 
Last edited:
  1. What food object?
  2. What searchscope?
  3. What player?
  4. Explain what your code is doing that it should not.
  5. What line does the error appear on?
Have you tried debugging? If you wrote this, you should know what its doing. This looks like an edited script of the find nearest enemy...

Evil code
C#:
while (Notarget)
      {
          if (canChoose)
      {
When do you drop out of the loop, more so; why do you even need a loop?
 
Are you sure that closestConsumable is not null by the time you get to line 31 and/or 33?
 
Back
Top Bottom