public string hook ;

描述

钩子属性可用于指定当 SyncVar 更改客户端上的值时要调用的函数。

这可确保所有客户端从其他客户端接收适当的变量。

//Attach this to the GameObject you would like to spawn (the player).
//Make sure to create a NetworkManager with an HUD component in your Scene. To do this, create a GameObject, click on it, and click on the Add Component button in the Inspector window.  From there, Go to Network>NetworkManager and Network>NetworkManagerHUD respectively.
//Assign the GameObject you would like to spawn in the NetworkManager.
//Start the server and client for this to work.

//Use this script to send and update variables between Networked GameObjects using UnityEngine; using UnityEngine.Networking;

public class Health : NetworkBehaviour { public const int m_MaxHealth = 100;

//Detects when a health change happens and calls the appropriate function [SyncVar(hook = "OnChangeHealth")] public int m_CurrentHealth = m_MaxHealth; public RectTransform healthBar;

public void TakeDamage(int amount) { if (!isServer) return;

//Decrease the "health" of the GameObject m_CurrentHealth -= amount; //Make sure the health doesn't go below 0 if (m_CurrentHealth <= 0) { m_CurrentHealth = 0; } }

void Update() { //If the space key is pressed, decrease the GameObject's own "health" if (Input.GetKey(KeyCode.Space)) { if (isLocalPlayer) CmdTakeHealth(); } }

void OnChangeHealth(int health) { healthBar.sizeDelta = new Vector2(health, healthBar.sizeDelta.y); }

//This is a Network command, so the damage is done to the relevant GameObject [Command] void CmdTakeHealth() { //Apply damage to the GameObject TakeDamage(2); } }
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961