- Home /
Unity Is Caling My Vector3 a Float?
Hello, I am working on creating a basic BOIDs AI system in Unity and I am having an error. Here is my code:
Collider[] colls = Physics.OverlapSphere(transform.position, 25f);
Vector3 aiEpicenter = Vector3.zero;
Vector3[] converted;
// Move to epicenter
for (int i = 0; i<colls.Length; i++) {
foreach (Collider coll in colls) {
aiLocations.Add(coll.transform.position);
}
converted = aiLocations.ToArray();
for (int b = 0; b<converted.Length; b++) {
converted[b] = new Vector3(converted[b].x / converted.Length, transform.position, converted[b].z / converted.Length);
}
for (int a = 0; a<converted.Length; a++) {
aiEpicenter = aiEpicenter + converted[i];
}
}
transform.LookAt(aiEpicenter);
transform.position += transform.forward * speed * Time.deltaTime;
For some reason in the inspector, though, it is saying Line 12 of the provided code is a float and therefore cannot be turned into a Vector3. If anyone could help, that would be greatly appreciated!
Answer by Bunny83 · Jan 26, 2019 at 07:23 PM
Your line reads:
converted[b] = new Vector3(
converted[b].x / converted.Length,
transform.position,
converted[b].z / converted.Length
);
As you can see as the second argument to the Vector3 constructor you're passing transform.position
(a Vector3) but a float value is required. You probably wanted to pass transform.position.y
instead.
Though your whole approach is way too complicated. You can simply add up all positions and divide the result once at the end. There's no need for a List and another Array or two loops. Further more your outer loop is completely pointless. You're interating through all collisions already inside the loop. So you're doing the same things way too often. To find the center of the objects, just do:
Collider[] colls = Physics.OverlapSphere(transform.position, 25f);
Vector3 aiEpicenter = Vector3.zero;
foreach (Collider coll in colls)
{
aiEpicenter += coll.transform.position;
}
aiEpicenter /= colls.Length;
aiEpicenter.y = transform.position.y;
transform.LookAt(aiEpicenter);
transform.position += transform.forward * speed * Time.deltaTime;
Answer by Ymrasu · Jan 26, 2019 at 07:20 PM
converted[b] = new Vector3(converted[b].x / converted.Length, transform.position, converted[b].z / converted.Length);
transform.position is a vector3, and it should be a float in that position. Did you mean to put transform.postion.y?