目录
42、机器人的产生和创建
机器人实现逻辑
![](https://img-blog.csdnimg.cn/6017ba42393c48ec97f3c36c21e11883.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAfkxvbWlzc34=,size_20,color_FFFFFF,t_70,g_se,x_16)
新建BotSpawner.cs,并添加代码
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
using Random = UnityEngine.Random;
public class BotSpawner : MonoBehaviour
{
public int maxBots; // 机器人最大数量
public GameObject[] prefabs;
private void Awake() // 如果是单人游戏就加入机器人,是联机就不加入
{
if (NetworkManager.numPlayers > 1) enabled = false;
}
private void Start() // 要加Private,否则没反应
{
StartCoroutine(SpawnBot());
}
IEnumerator SpawnBot()
{
yield return new WaitForSeconds(1);
for (int i = 0; i < maxBots; ++i)
{
int randIndex = Random.Range(0, prefabs.Length);
GameObject obj = Instantiate(prefabs[randIndex], Vector3.zero, Quaternion.identity);
PlayerBot p = obj.GetComponent<PlayerBot>();
p.teamIndex = GameManager.GetInstance().GetTeamFill();
NetworkServer.Spawn(obj, prefabs[randIndex].GetComponent<NetworkIdentity>().assetId);
GameManager.GetInstance().size[p.teamIndex]++;
GameManager.GetInstance().ui.OnTeamSizeChanged(SyncList<int>.Operation.OP_SET, p.teamIndex, 0 ,0 );
yield return new WaitForSeconds(0.25f);
}
}
}
![](https://img-blog.csdnimg.cn/3fef110cf9064bacaca3a812b6dab96a.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAfkxvbWlzc34=,size_20,color_FFFFFF,t_70,g_se,x_16)
新建PlayerBot.cs,并添加代码
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using Random = UnityEngine.Random;
public class PlayerBot : Player
{
public float range = 6f; // 射程
private List<GameObject> inRange = new List<GameObject>();
private NavMeshAgent agent;
private Vector3 targetPoint;
private float nextShot;
private bool isDead = false;
private void Start()
{
camFollow = Camera.main.GetComponent<CamFollow>();
agent = GetComponent<NavMeshAgent>();
agent.speed = MoveSpeed;
targetPoint = GameManager.GetInstance().GetSpawnPosition(teamIndex);
agent.Warp(targetPoint);
Team team = GameManager.GetInstance().teams[teamIndex];
for (int i = 0; i < renderers.Length; ++i) renderers[i].material = team.material;
hpImage.color = team.color;
myName = label.text = "Bot" + System.String.Format("{0:0000}", Random.Range(1, 9999));
health = maxHealth;
shield = 0;
//OnHealthChange(health);
//OnShieldChange(shield);
}
}
更新Player.cs
using System;
using UnityEngine;
using UnityEngine.UI;
using Mirror;
public class Player : NetworkBehaviour
{
……
[HideInInspector] public CamFollow camFollow;
……
}
![](https://img-blog.csdnimg.cn/607e3ad5964548f1b7adcc1950b51848.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAfkxvbWlzc34=,size_20,color_FFFFFF,t_70,g_se,x_16)
测试
![](https://img-blog.csdnimg.cn/106bfed66c1a4d1aac3ac1746b99d88a.gif)