访问同一脚本中对象的属性

本文关键字:对象 属性 脚本 访问 | 更新日期: 2023-09-27 18:04:18

我有一个脚本,搜索一堆对象的地图,根据距离排序,并选择最近的一个作为目标,分配最近的一个为"SelectedTarget"

我需要将"mass"属性附加到"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++;
}

访问同一脚本中对象的属性

我想你正在寻找GetComponent方法

你会得到这样的内容:

mass = SelectedTarget.GetComponent<NameOfScriptThatHasMassProperty>().mass;