Hello, so the issue I’m having is when my “AI” starts i want it to “look for food” and it does but after it finds the first piece I get an error as it doesn’t look for another one I figured I could use an array of transforms for the game objects but unity wont allow me to do that so I’m not sure where to go from here.
Thank you for any help in advance.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemyFindFood : MonoBehaviour
{
public Transform target;
public int moveSpeed = 3;
public int rotationSpeed = 3;
public Transform myTransform;
void Awake()
{
myTransform = transform;
}
// Start is called before the first frame update
void Start()
{
target = GameObject.FindGameObjectWithTag("Food").transform;
}
// Update is called once per frame
void Update()
{
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
@Magso I tried that earlier and I was getting an error it wouldn’t allow me to use Transform but idk i guess i did something else wrong but now I got an error for invalid expression term [ in front of index?
It might be best to not assign this to an array at all, but rather have the AI look for the closest next object via a function – and call that function at start, and whenever it ate one. This would also make it flexible towards e.g. food items disappearing and such. Also, you may want to have it find the closest food first, not just any:
using UnityEngine;
using System.Linq;
public class FoodFinding : MonoBehaviour
{
Transform foodTarget = null;
public void Start()
{
SetNextFoodTarget();
}
void Update()
{
if (foodTarget != null)
{
// Move towards foodTarget.
// If found, call SetNextFoodTarget() again.
}
}
void SetNextFoodTarget()
{
GameObject[] foodsByCloseness = GameObject.FindGameObjectsWithTag("Food").OrderBy(
x => Vector3.Distance(transform.position, x.transform.position)
).ToArray();
if (foodsByCloseness.Length >= 1)
{
foodTarget = foodsByCloseness[0].transform;
print("Found food target " + foodTarget.name);
}
}
}