是否可以调用数组中的所有对象?或者只使用数字?
public void Update()
{
Targetting ge = (Targetting)target.GetComponent("Targetting");
enemies = ge.targets;
float attackDistanceP = Vector3.Distance(target.transform.position, transform.position);
foreach (Transform enemy in enemies)
{
float enemyDistance = Vector3.Distance(enemy.transform.position, transform.position);
print(enemyDistance);
}
Debug.DrawLine(transform.position, waypointPosition, Color.black);
if (attackDistanceP < 8)
disableNow = true;
if (attackDistanceP > 8)
disableNow = false;
}
我想调用enemies []数组中的所有对象。这样所有的敌人都能看到对方。但我不想让他们看到自己。我使用GameObject.FindGameObjectsWithTag在另一个脚本中填充数组。
答案 0 :(得分:1)
foreach(Transform enemy in enemies){
if (enemy == this.transform) continue; // skip me
float enemyDistance = Vector3.Distance(enemy.transform.position, transform.position);
print(enemyDistance);
}
答案 1 :(得分:1)
您的一些过早优化:
using System.Collections.Generic;
public Transform trans;
Targetting ge;
void Start() {
trans = transform;
ge = target.GetComponent<Targetting>();
}
void Update () {
enemies = ge.targets;
float attackDistanceP = (target.trans.position - trans.position).sqrMagnitude; // save a square root
foreach(Transform enemy in enemies){
if (enemy == trans) continue; // skip me
float enemyDistance = (enemy.trans.position - trans.position).sqrMagnitude; // save a square root
print(enemyDistance);
}
Debug.DrawLine (trans.position, waypointPosition, Color.black);
if(attackDistanceP < 64)
disableNow = true;
if(attackDistanceP > 64)
disableNow = false;
}