I’m getting a error when referencing transform.position from the potentialTargList array of GameObjects. I’m trying to sort the array by distance.
Error CS1061 ‘GameObject[ ]’ does not contain a definition for ‘transform’ and no accessible extension method ‘transform’ accepting a first argument of type ‘GameObject[ ]’ could be found (are you missing a using directive or an assembly reference?)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class Test : MonoBehaviour
{
private GameObject[ ] potentialTargList;
I mean Use Code Tags so we can see your code better ^^,
in your linq loop your not accessing single objects, you try to access the List.transform.position which wont work,
OrderBy is well known about GameObjects since they are classes as others,
your “foreach” statement will still drop a syntax error since you dont have a body where you want to describe the desired behaviour for ea. point in the list
You’re saying I need to make a more elaborate algorithm that looks at each objects distance and and then maybe build a new array in the proper order? So I can make a struct array with object and distance then sort the array. Then build a new array according to distance?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class Test : MonoBehaviour
{
private GameObject[] potentialTargList;
void Update()
{
potentialTargList = EnemySpawner.enemyList.ToArray();
if (potentialTargList != null)
{
FindClosestEnemy();
}
}
void FindClosestEnemy()
{
potentialTargList = potentialTargList.OrderBy(point => Vector3.Distance(this.transform.position, potentialTargList.transform.position)).ToArray();
foreach (GameObject point in potentialTargList)
Debug.Log(point.name);
}
}
you try to get the Distance from “THIS.transform.position” which is fine but you compare it with your entire “LIST” which will never work since you can compare only 2 objects with ea. other,
you basically say “Order me the List → potentialTarget” by EACH “point” → Distance,
and then its like a foreach loop,
you need to calculate the distance foreach point.transform.position,
it loops through the list 1 by 1 , not all at the same time,
i hope my explaining skills are not to embaressing X)