【UNET自学日志】Part12 僵尸

时间:2022-01-14 03:54:04

随意的新建一个物体来当僵尸,记得和平时游戏添加的敌人一样,加上NavMeshAgent组件来追踪玩家

在zombie上添加NetworkIdentity和NetworkTransform,新建脚本Zombie_Target添加到Zombie上,将Zombie作为一个新的Prefab

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class Zombie_Target : NetworkBehaviour {

    private NavMeshAgent agent;
    private Transform myTransform;
    private Transform targetTransform;
    private LayerMask raycastLayer;
    private float radius = 100;


	// Use this for initialization
	void Start () 
    {
        agent = GetComponent<NavMeshAgent>();
        myTransform = transform;
        raycastLayer = 1 << LayerMask.NameToLayer("Player");
	}
	
	// Update is called once per frame
	void Update ()
    {
        SerachToTarget();
        MoverToTarget();
	}

    void SerachToTarget()
    {
        if (!isServer)
        {
            return;
        }

        if (targetTransform == null)
        {
            Collider[] hitColliders = Physics.OverlapSphere(myTransform.position, radius, raycastLayer);

            if (hitColliders.Length > 0)
            {
                int randomint = Random.Range(0, hitColliders.Length);
                targetTransform = hitColliders[randomint].transform;
            }
        }

        if (targetTransform != null && targetTransform.GetComponent<BoxCollider>().enabled == false)
        {
            targetTransform = null;
        }
    }

    void MoverToTarget()
    {
        if (targetTransform != null && isServer)
        {
            SetNavDestination(targetTransform);
        }
    }

    void SetNavDestination(Transform dest)
    {
        agent.SetDestination(dest.position);
    }
}
新建一个空物体作为Zombie 的Spawn点

新建脚本GameManaer_ZombieSpawner,添加到GameManager上,同时记得添加一个NetworkIdentity

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class GameManaer_ZombieSpawner : NetworkBehaviour {

    [SerializeField]
    GameObject zombiePrefab;
    [SerializeField]
    GameObject zombieSpawn;
    private int counter;
    private int numberOfZombies = 10;

    public override void OnStartServer()
    {
        for (int i = 0; i < numberOfZombies; i++)
        {
            SpawnZombie();
        }
    }

    void SpawnZombie()
    {
        //counter

        GameObject go = GameObject.Instantiate(zombiePrefab, zombieSpawn.transform.position, Quaternion.identity) as GameObject;
        NetworkServer.Spawn(go);
    }

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}
将对应的ZombiePrefab和ZombieSpawn设置好

接下来记得在NetworkManager中的SpawnInfo的Registered Spawnable Prefabs中添加Zombie的Prefab即可


不过遇到点问题,不知道什么每次重新打开的时候zombie预制件的注册又变成了empty的状态= =怎么说没就没。。。