我有一个脚本在地图上搜索一堆对象,根据距离对它们进行排序,并选择最近的一个作为目标,将最近的一个指定为" SelectedTarget"
我需要得到"质量"物业附属于" SelectedTarget"所以我可以让AI决定它是否会追逐" SelectedTarget"或逃跑。我已经在这几个小时,任何帮助将不胜感激。提前谢谢!
这是我的代码:
public class PredatorScript : MonoBehaviour {
public float mass = 1;
public float size = 1;
public List<Transform> FoodTargets;
public Transform SelectedTarget;
private Transform myTransform;
Transform target;
public float speed = 1;
public float sight = 1;
private float distance = 0;
private int counter = 0;
void Start () {
FoodTargets = new List<Transform>();
SelectedTarget = null;
myTransform = transform;
AddAllFood ();
}
public void AddAllFood()
{
GameObject[] Foods = GameObject.FindGameObjectsWithTag("Herbivore");
foreach (GameObject enemy in Foods)
AddTarget (enemy.transform);
}
public void AddTarget(Transform enemy)
{
FoodTargets.Add (enemy);
}
private void SortTargetsByDistance()
{
FoodTargets.Sort (delegate(Transform t1, Transform t2) {
return Vector3.Distance(t1.position, myTransform.position)
.CompareTo(Vector3.Distance(t2.position, myTransform.position));
});
}
private void TargetEnemy()
{
if (SelectedTarget == null) {
SortTargetsByDistance ();
SelectedTarget = FoodTargets [0];
}
else {
SortTargetsByDistance ();
SelectedTarget = FoodTargets [0];
}
}
void Update(){
TargetEnemy ();
distance = Vector3.Distance(transform.position, SelectedTarget.transform.position);
mass = SelectedTarget.trasform.mass; <------- This is what i've been trying
if (distance < sight)
{
transform.LookAt (transform.position +
new Vector3 (0, 0, 1),
transform.position - SelectedTarget.transform.position); //Face target
transform.Translate (Vector3.down * speed * Time.deltaTime); //movement forwards
}
else {
if (counter >= 120){
transform.Rotate(0, 0, Random.Range(0, 360));
counter = 0;
}
transform.Translate (Vector3.down * (speed/3) * Time.deltaTime);
counter++;
}
答案 0 :(得分:1)
我认为您正在寻找GetComponent方法
所以你会有这样的事情:
mass = SelectedTarget.GetComponent<NameOfScriptThatHasMassProperty>().mass;