1.实验的目的和要求
掌握Unity脚本的主要内容,通过游戏物体索引方法,查找相关信息的游戏物体。
2.实验内容
(1)设定多个游戏物体的血量值,利用Object类的方法查找血量最少的游戏物体,标为红色。
(2)查找距离最近的游戏物体,标为蓝色。
3.主要代码
(1)enemy脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemy : MonoBehaviour
{
public int HP;
}
(2)FindEnemyDemo脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FindEnemyDemo : MonoBehaviour
{
private void OnGUI()
{
if (GUILayout.Button("查找血量最少的敌人"))
{
enemy[] allenmy = Object.FindObjectsOfType<enemy>();
enemy min = FindEnemyByMinHP(allenmy);
min.GetComponent<MeshRenderer>().material.color = Color.red;
}
if (GUILayout.Button("查找距离最近的敌人"))
{
enemy[] allenmy = Object.FindObjectsOfType<enemy>();
enemy min = FindEnemyByMinDistance(allenmy);
min.GetComponent<MeshRenderer>().material.color = Color.blue;
}
}
public enemy FindEnemyByMinHP(enemy[] allenemy)
{
enemy min = allenemy[0];
for(int i = 1; i < allenemy.Length; i++)
{
if (min.HP > allenemy[i].HP)
{
min = allenemy[i];
}
}
return min;
}
public enemy FindEnemyByMinDistance(enemy[] allenemy)
{
enemy min = allenemy[0];
float minDistance = Vector3.Distance(this.transform.position, min.transform.position);
for (int i = 1; i < allenemy.Length; i++)
{
float newDistance = Vector3.Distance(this.transform.position, allenemy[i].transform.position);
if (minDistance > newDistance)
{
min = allenemy[i];
minDistance = newDistance;
}
}
return min;
}
}
4.实验结果