1.首先我们设置一个脚本enemy,它里面只有一个值那就是HP显示生命值。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemy : MonoBehaviour
{
public int HP=0;
// Start is called before the first frame update
}
2.把他挂载到所以敌人的组件中去
3.新建一个脚本去找最小生命值的敌人,我们把它挂载到另一个物体上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript2 : MonoBehaviour
{
public enemy[] agameObject;
public enemy low;
public void Start()
{
agameObject = Object.FindObjectsOfType<enemy>();
low = agameObject[0];
for (int i = 0; i < agameObject.Length; i++)
{
if (agameObject[i].HP < low.HP)
{
low = agameObject[i];
Debug.Log("1");
}
}
low.GetComponent<MeshRenderer>().material.color = Color.red;
}
}
如上,其实是查找的Enemy类型的对象(引用).找到后可以用GetComponent函数寻找物体身上的其他组件,然后例如更改颜色或者其他的设置.