Home > other >  Unity method to find closest GameObject gives over 20 errors
Unity method to find closest GameObject gives over 20 errors

Time:07-10

void FindClosestPoint()
    {
        public float DistanceToClosestPoint = Mathf.Infinity;
        public GameObject closestPoint = null;
        GameObject[] points = GameObject.FindGameObjectsWithTag("Swing");
        foreach (GameObject point in points)
        {
            float DistanceToPoint = (point.transform.position - this.transform.position).sqrMagnitude;
            if(DistanceToPoint < DistanceToClosestPoint)
            {
                DistanceToClosestPoint = DistanceToPoint;
                closestPoint = point;
            }
        }


    }

This gives me an error on the foreach and in and if and the curly bracket bellow if where it says Invalid Token and on the in it says Tuple must contain two elements. It also says point does not exist in the current context and this. is not available in the context. bellow if it gives me an error on both = and both the ; which says invalid Token. I have tried to fix this multiple times but i think it just corrupts the entire file because the start and update functions get broken.

CodePudding user response:

I had to stare at this one for a few minutes to find the problem.

public is not valid for local variables - only for class members. Remove that and it should work fine. (If you understand what public or private or internal mean, this will make perfect sense.)

void FindClosestPoint()
{
    float DistanceToClosestPoint = Mathf.Infinity;
    GameObject closestPoint = null;
    GameObject[] points = GameObject.FindGameObjectsWithTag("Swing");
    foreach (GameObject point in points)
    {
        float DistanceToPoint = (point.transform.position - this.transform.position).sqrMagnitude;
        if(DistanceToPoint < DistanceToClosestPoint)
        {
            DistanceToClosestPoint = DistanceToPoint;
            closestPoint = point;
        }
    }

}

The "Invalid token" error means to say that you can't use public on a local variable. When the compiler sees public, it assumes you're trying to declare a class member (field, method, property, etc.), so it generates a bunch of seemingly-weird errors that don't really describe the problem. This one was not obvious to me.

  • Related