An example of unet, the official built-in network of unity

1, Add network management component

Create a new network manager. The network manager will control the network state of the project, including game state management, generation point management, scene management, pairing and allowing access to relevant information. For advanced users, you can derive a class from NetworkManager to define the behavior of components and extend the network manager not covered

2, To create a character prefab:

Introduction to NetworkIdentity component: the most basic component of a network object. The client and the server confirm whether it is an object (netID). It is also used to indicate various states, such as whether it is a server, whether it is a client, whether it has permissions, whether it is a local player, etc.

3, Control character movement

4, Control character shooting

Setting of bullet prefabrication

Bullet generation:

Why not synchronize bullet destruction? Because the server is the mother. If the server is destroyed, the client will be destroyed naturally

5, Decrease in blood volume

Making blood bar:

Note: the blood volume is reduced because the server is the parent. In order to prevent the client bullets from colliding with the role when the parent bullets are destroyed, the blood volume can not be reduced in time, resulting in data synchronization. Therefore, the control and detection of the blood volume can only be calculated on the server and synchronized to the client

 

Bullet add collision script

  

6, Reincarnation of control figures

Set regeneration point:

  

7, Control the generation of enemies

  

Enemies are generated on each client, so enemies are generated on the server, and the generated enemies are synchronized to the client

  

RPC is a remote call (the server and the client call each other). It calls a method on the server side, uses the combined method, and if you want to call a method on the client side, uses the ClientRPC,

SyncVar is to synchronize a variable, such as the life of the main character,

Hook, which specifies a string parameter. This parameter specifies the name of the method. When the value of the variable changes, the method specified by hook is called.

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

public class PlayerController : NetworkBehaviour {

    public GameObject bulletPrefab;
    public Transform bulletSpawn;	
	// Update is called once per frame
	void Update () {
        if (isLocalPlayer == false)
        {
            return;
        }
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");

        transform.Rotate(Vector3.up * h * 120 * Time.deltaTime);
        transform.Translate(Vector3.forward * v * 3 * Time.deltaTime);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            CmdFire();
        }
	}  
    [Command]//This command, each client will call this method, but the running is on the server side
    void CmdFire()//This method needs to be called in the server and must start with Cmd
    {
        // The generation of bullets needs to be completed by the server, and then the bullets are synchronized to each client
        GameObject bullet = Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation) as GameObject;
        bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 10;//Initial speed
        Destroy(bullet, 2);
        NetworkServer.Spawn(bullet);//Network generated bullets are synchronized to the client. Without this code, another client can't see the generated bullets
      //Bullet belongs to a thing of the network. This sentence only distributes the bullet object to the client, but does not give the bullet speed to the client
    }
    public override void OnStartLocalPlayer()
    {
        //This method will only be called from the local role when the role is created
        GetComponent<MeshRenderer>().material.color = Color.blue;
    }
}
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.Networking;
public class Health : NetworkBehaviour {
    public const int maxHealth = 100;
    //The following SyncVar synchronization function will be detected all the time, and this method will be called after detection, which will be called by each client
    [SyncVar(hook="OnChangeHealth") ]
    public int currentHealth = maxHealth;
    public Slider healthSlider;
    public bool destroyOnDeath = false;//true means enemy, destroy   
    public void TakeDamage(int damage) //The following is the method executed on the server side
    {
        if (isServer == false) return;// The processing of blood volume is only performed on the server side
        currentHealth -= damage;
        if (currentHealth <= 0)
        {
            if (destroyOnDeath) //It's the enemy. Destroy it
            {
                Destroy(this.gameObject); return;
            }
             currentHealth = maxHealth;//After death, the current blood volume returns to the maximum            
            RpcRespawn();//If it's not the enemy, we need to be reborn
        }
    }
    //The above defines synchronization variables and updates the changed variables
    void OnChangeHealth(int health)
    {
        healthSlider.value = health / (float)maxHealth;
    }
    //Set regeneration point
    private NetworkStartPosition[] spawnPoints;
    void Start()
    {
        if (isLocalPlayer)
        {
            spawnPoints = FindObjectsOfType<NetworkStartPosition>();
        }
    }
    /// <summary>
    ///Character regeneration. This method should be called on the client
    /// </summary>
    [ClientRpc]
    void RpcRespawn()
    {
        if (isLocalPlayer == false) return;

        Vector3 spawnPosition = Vector3.zero;

        if (spawnPoints != null && spawnPoints.Length > 0)
        {
            spawnPosition = spawnPoints[Random.Range(0, spawnPoints.Length)].transform.position;
        }
        transform.position = spawnPosition;
    }
}

 

using UnityEngine;
using System.Collections;

public class Bullet : MonoBehaviour {
    void OnCollisionEnter(Collision col)
    {
        GameObject hit = col.gameObject;
        Health health = hit.GetComponent<Health>();

        if (health != null)
        {
            health.TakeDamage(10);
        }
        Destroy(this.gameObject);
    }

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

public class EnemySpawner : NetworkBehaviour {

    public GameObject enemyPrefab;
    public int numberOfEnemies;
    public override void OnStartServer()
    {
        for (int i = 0; i < numberOfEnemies; i++)//Number of enemies
        {
            Vector3 position = new Vector3(Random.Range(-6f, 6f), 0, Random.Range(-6f, 6f));

            Quaternion rotation = Quaternion.Euler(0, Random.Range(0, 360), 0);

            GameObject enemy = Instantiate(enemyPrefab, position, rotation) as GameObject;

            NetworkServer.Spawn(enemy);//Sync to client, sync to network
        }  
    }
	

}

 

 

 

 

Tags: network

Posted on Mon, 22 Jun 2020 04:05:16 -0400 by zaneosak