天天看點

Unet下

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class playerController :NetworkBehaviour {

    public float turnSpeed=120;
    public float moveSpeed=3;
    // Use this for initialization

    List<GameObject> bulletPools=new List<GameObject>();
    public int poolsSize;
    public GameObject bulletPre;
    public Transform firePos;

     float FireTime=0;
     public float FireRate=0.2f;
    private void Awake()
    {
        for (int i = 0; i <poolsSize; i++)
        {
            GameObject go = Instantiate(bulletPre, firePos.position, firePos.rotation);
            bulletPools.Add(bulletPre);
            go.gameObject.SetActive(false);
        }
    }
    void Start ()
    {
		
	}
	
	// Update is called once per frame
	void Update ()
    {
        if (isLocalPlayer==false)
        {
            return;

        }
        else
        {
            float H = Input.GetAxis("Horizontal");
            float V = Input.GetAxis("Vertical");
            transform.Rotate(Vector3.up * turnSpeed * H * Time.deltaTime);
            transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime*V);
            if (Input.GetMouseButton (0))
            {  CmdShoot();}
        }

     
	}

    ///
    public override void OnStartLocalPlayer()
    {
        //這個方法 隻會在本地 調用。
        base.OnStartLocalPlayer(); 
        GetComponent<MeshRenderer>().material.color = Color.blue;
    }

[Command]//called in client,run in server
    void CmdShoot()
    {
      //這個方法需要 在Server中調用
            FireTime+=Time.deltaTime;
            if(FireTime>FireRate)
            {
             GameObject bullet =  Instantiate(bulletPre,firePos.position,firePos.rotation);
               
             bullet.GetComponent<bullet>().Fire(bullet.transform.forward*30f);
             FireTime=0;
             Destroy(bullet,2f);
              NetworkServer.Spawn(bullet);
               
            }

           
        
    }

    public GameObject GetBulletInPool()
    {

        bool isHere=false;
        GameObject bullet=null;
        foreach (var i in bulletPools)
        {
            if (!i.gameObject.activeSelf)
            {
                isHere = true;
                bullet=i;
                break;
            }
        }
        if (isHere)
        {
            bullet.transform.position=firePos.position;
            bullet.transform.rotation=firePos.rotation;
            return bullet;
        }
        else
        {
            bullet = Instantiate(bulletPre, firePos.position, firePos.rotation)as GameObject;

            bulletPools.Add(bullet);
            bullet.gameObject.SetActive(false);
            return bullet;
        }
    } 
}
           

Unet學習:

1 場景中有空物體挂載NetWokManager 和NetWork Manager HUD(負責UI)。

2 要在伺服器端生成的物品 都要加上 NetWorkIdentity 才可以指派給Registered Spawnable Prefabs。

3 PlayerPrefabs 要更新資訊加上 Network Transform元件與 NetworkIdentity元件 。

勾選 Local Player Authority 本地權限 表示是用戶端。

NetworkIdentity是用于網絡識别的辨別符, 有伺服器權限Server Only(不能被本地權限玩家設定權限),和本地權限Local Player Authority。

另外想要在客服端/伺服器 執行一些操作,可以讓腳本繼承 NetworkBehaviour 類。

通過 isServer/isClient 變量 進行判斷 或者 通過 添加特性。

[Commd] 用戶端調用,伺服器運作,下面的方法要加Cmd字首,

[clientRpc]  用戶端  下面方法要加Rpc字首 表示 用戶端調用。

網絡遊戲 基本上遊戲邏輯都在伺服器調用,與角色行為相關的都在LocalPlayer調用。

NewtworkIdentity表示 隻會在服務端運作,但是可以擁有 本地玩家權限。

OnStartSevert 在伺服器建立時 調用。

NetworkStartPosition 元件,  遊戲啟動時, 玩家生成的位置,需要在NetworkManager中設定 玩家生成方法為 Round Robin

Unet下

https://docs.unity3d.com/ScriptReference/Networking.NetworkBehaviour.html

NetworkBehaviour Api

Properties

connectionToClient The NetworkConnection associated with this NetworkIdentity. This is only valid for player objects on the server.
connectionToServer The NetworkConnection associated with this NetworkIdentity. This is only valid for player objects on the server.
hasAuthority This returns true if this object is the authoritative version of the object in the distributed network application.
isClient Returns true if running as a client and this object was spawned by a server.
isLocalPlayer This returns true if this object is the one that represents the player on the local machine.
isServer Returns true if this object is active on an active server.
localPlayerAuthority This value is set on the NetworkIdentity and is accessible here for convenient access for scripts.
netId The unique network Id of this object.
playerControllerId The id of the player associated with the behaviour.
connectionToClient  connectionToServer    這連個都是隻讀的,

hasAuthority  是 否有權限 分布網絡應用中

isClient 是否用戶端 通過 伺服器生成的

isLocalPlayer 是否本地玩家

isServer 是否 服務端

localPlayerAuthority  NetworkIdentity 中 是否 有本地玩家權限

netId   網絡id

playerControllerId   與行為相關的 玩家id

Public Methods

ClearAllDirtyBits This clears all the dirty bits that were set on this script by SetDirtyBits();
GetNetworkChannel This virtual function is used to specify the QoS channel to use for SyncVar updates for this script.
GetNetworkSendInterval This virtual function is used to specify the send interval to use for SyncVar updates for this script.
InvokeCommand Manually invoke a Command.
InvokeRPC Manually invoke an RPC function.
InvokeSyncEvent Manually invoke a SyncEvent.
OnCheckObserver Callback used by the visibility system to determine if an observer (player) can see this object.
OnDeserialize Virtual function to override to receive custom serialization data. The corresponding function to send serialization data is OnSerialize().
OnNetworkDestroy This is invoked on clients when the server has caused this object to be destroyed.
OnRebuildObservers Callback used by the visibility system to (re)construct the set of observers that can see this object.
OnSerialize Virtual function to override to send custom serialization data. The corresponding function to send serialization data is OnDeserialize().
OnSetLocalVisibility Callback used by the visibility system for objects on a host.
OnStartAuthority This is invoked on behaviours that have authority, based on context and NetworkIdentity.localPlayerAuthority.
OnStartClient Called on every NetworkBehaviour when it is activated on a client.
OnStartLocalPlayer Called when the local player object has been set up.
OnStartServer This is invoked for NetworkBehaviour objects when they become active on the server.
OnStopAuthority This is invoked on behaviours when authority is removed.
PreStartClient An internal method called on client objects to resolve GameObject references.
SetDirtyBit Used to set the behaviour as dirty, so that a network update will be sent for the object.

 方法就比較多了  

ClearAllDirtyBits 清除在腳本上的所有标志位 虛函數

GetNetworkChannel 擷取網絡通道 此虛拟函數用于列舉用于此腳本的[SyncVar]更新的QoS通道。 SyncVar 同步變量 特性 傳回值是int 傳回是 此腳本的 QoS通道  虛函數

GetNetworkSendInterval 此虛拟函數用于傳回要為SyncVar使用的發送間隔

傳回 在同步更新之間的發送間隔(秒)

InvokeCommand   public virtual bool InvokeCommand(int cmdHash, NetworkReader reader);

手動調用 Command(伺服器) 參數是 Command的哈希名,以及傳遞給Command的參數

InvokeRPC  public virtual bool InvokeRPC(int cmdHash, NetworkReader reader);

跟上面類似, 隻不過是調用用戶端。RPC(Remote Procedure Call)就是遠端過程調用 的意思 ,就是遠端調用

InvokeSyncEvent   public virtual bool InvokeSyncEvent(int cmdHash, NetworkReader reader);

手動調用 同步事件  同步事件哈希名  傳遞給同步事件參數

OnCheckObserver   public virtual  bool OnCheckObserver(NetworkConnection conn)

通過可見系統使用回調來确定觀察者(玩家)是否可以看到這個對象。

參數是 玩家的網絡連接配接

OnDeserialize   public virtual void OnDeserialize(NetworkReader reader, bool initialState);

虛函數,用于覆寫以接收自定義序列化資料。相應的

發送序列化資料的函數是OnSerialize()。

參數 reader 從(stream)流中 讀取 , 初始狀态

OnNetworkDestroy  public void OnNetworkDestroy();

當伺服器有對象要被摧毀時 在用戶端上調用

OnRebuildObservers public bool OnRebuildObservers(HashSet<NetworkConnection> observers, bool initialize);

可見系統 用來(重)一組 可以看到這個物體的觀察者的回調

這個回調的實作應該向觀察者添加可以看到這個對象的玩家的網絡連接配接。

OnSerialize  public bool OnSerialize(Networking.NetworkWriter writer, bool initialState);

 虛函數  覆寫到 發送 自定義 序列化 資料,  相對應的發送 序列化資料的函數 是 OnDeserialize().反序列化

 Writer 用來 寫入流   initialState  初始狀态 

初始狀态 标志位 是有用于去區分 第一次序列化對象 與  可以發送的增量更新。

第一次将一個對象 發送給客服,它必須包含一個完整狀态快照,但是後續更新隻包含增量改變,可以節省帶寬。

注意 當初始狀态為true,Synvarhook函數 是不會被調用的,隻在增量更新時調用。

如果一個類有 SyncVars 同步變量,那麼 啟用和反序列化這個函數會被自動加進 類裡。

是以 一個有同步變量的類  也不能有自定義的序列化函數。

這個序列化 函數 應該傳回true,表示應該發送更新。如果傳回true 那麼 腳本 的标志位 被設定到0;如果它傳回false

那麼 這個标志位,沒有被改變。這允許腳本随着時間積累,多次改變,并且當系統已經準備就發送。而不是每一貞;

OnSetLocalVisibility   public void OnSetLocalVisibility(bool vis);

可見系統用于 在主機上對象的回調

vis  新的可見狀态

OnStartAuthority public void OnStartAuthority();

在 一個有權限的腳本上調用 ,基于環境,和NetworkIdentity.localPlayerAuthority 本地玩家權限

會在 OnStartSever 和OnStartClient 執行 之後 調用

當  NetworkIdentity.AssignClientAuthority 在伺服器上被調用時,這将會在擁有自己對象的用戶端調用.

當 一個對象被NetworkServer.SpawnWithClientAuthority生成的 ,這将 x會在擁有自己對象的用戶端調用。

OnStartClient  在用戶端啟用時調用每一個NetworkBehaviour

 主機上的對象有這個函數調用,因為主機上有本地用戶端。當這個函數在用戶端被調用時, 可以保證正确初始同步變量的值,并使用伺服器最近的一個狀态初始化。

OnStartLocalPlayer   public void OnStartLocalPlayer();

當本地玩家對象被建立時調用

在OnStartClient() 執行後 調用,因為 它是被從伺服器上的所有權消息觸發的。

這是一個對本地玩家激活元件或者功能的合适地方,比如 Input 和相機。

OnStartServer  public void OnStartServer();

當NetworkBehaviour對象 在伺服器啟用時 ,會被調用。

這個 可以被場景裡的NetworkSever.Listen() 的對象 觸發,或者被NetWorkServer.Spawn()動态生成的對象觸發。

這将會在 主機上的對象 和 專用伺服器上的對象 上被調用

OnStopAuthority public void OnStopAuthority();

當 對象 的 權限被移除時在behaviours 上調用

當 在伺服器上調用 NetworkIdentity.RemoveClientAuthority,就會在擁有這個對象的用戶端上調用。 

PreStartClient  public void PreStartClient();

一個内部的方法 調用用戶端對象,去解析 遊戲對象的引用

 把使用者的代碼放進這個函數中 這是不安全的。因為 它可能 被 網絡 系統的代碼生成過程替代掉。

SetDirtyBit   設定标志位 以便 對象可以發送網絡更新

Delegates

CmdDelegate Delegate for Command functions.
EventDelegate Delegate for Event functions.

Inherited Members

Properties

enabled Enabled Behaviours are Updated, disabled Behaviours are not.
isActiveAndEnabled Has the Behaviour had enabled called.
gameObject The game object this component is attached to. A component is always attached to a game object.
tag The tag of this game object.
transform The Transform attached to this GameObject.
runInEditMode Allow a specific instance of a MonoBehaviour to run in edit mode (only available in the editor).
useGUILayout Disabling this lets you skip the GUI layout phase.
hideFlags Should the object be hidden, saved with the scene or modifiable by the user?
name The name of the object.

Public Methods

BroadcastMessage Calls the method named methodName on every MonoBehaviour in this game object or any of its children.
CompareTag Is this game object tagged with tag ?
GetComponent Returns the component of Type type if the game object has one attached, null if it doesn't.
GetComponentInChildren Returns the component of Type type in the GameObject or any of its children using depth first search.
GetComponentInParent Returns the component of Type type in the GameObject or any of its parents.
GetComponents Returns all components of Type type in the GameObject.
GetComponentsInChildren Returns all components of Type type in the GameObject or any of its children.
GetComponentsInParent Returns all components of Type type in the GameObject or any of its parents.
SendMessage Calls the method named methodName on every MonoBehaviour in this game object.
SendMessageUpwards Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour.
CancelInvoke Cancels all Invoke calls on this MonoBehaviour.
Invoke Invokes the method methodName in time seconds.
InvokeRepeating Invokes the method methodName in time seconds, then repeatedly every repeatRate seconds.
IsInvoking Is any invoke on methodName pending?
StartCoroutine Starts a coroutine.
StopAllCoroutines Stops all coroutines running on this behaviour.
StopCoroutine Stops the first coroutine named methodName, or the coroutine stored in routine running on this behaviour.
GetInstanceID Returns the instance id of the object.
ToString Returns the name of the GameObject.

Static Methods

print Logs message to the Unity Console (identical to Debug.Log).
Destroy Removes a gameobject, component or asset.
DestroyImmediate Destroys the object obj immediately. You are strongly recommended to use Destroy instead.
DontDestroyOnLoad Makes the object target not be destroyed automatically when loading a new scene.
FindObjectOfType Returns the first active loaded object of Type type.
FindObjectsOfType Returns a list of all active loaded objects of Type type.
Instantiate Clones the object original and returns the clone.

Operators

bool Does the object exist?
operator != Compares if two objects refer to a different object.
operator == Compares two object references to see if they refer to the same object.

Messages

Awake Awake is called when the script instance is being loaded.
FixedUpdate This function is called every fixed framerate frame, if the MonoBehaviour is enabled.
LateUpdate LateUpdate is called every frame, if the Behaviour is enabled.
OnAnimatorIK Callback for setting up animation IK (inverse kinematics).
OnAnimatorMove Callback for processing animation movements for modifying root motion.
OnApplicationFocus Sent to all GameObjects when the player gets or loses focus.
OnApplicationPause Sent to all GameObjects when the application pauses.
OnApplicationQuit Sent to all game objects before the application quits.
OnAudioFilterRead If OnAudioFilterRead is implemented, Unity will insert a custom filter into the audio DSP chain.
OnBecameInvisible OnBecameInvisible is called when the renderer is no longer visible by any camera.
OnBecameVisible OnBecameVisible is called when the renderer became visible by any camera.
OnCollisionEnter OnCollisionEnter is called when this collider/rigidbody has begun touching another rigidbody/collider.
OnCollisionEnter2D Sent when an incoming collider makes contact with this object's collider (2D physics only).
OnCollisionExit OnCollisionExit is called when this collider/rigidbody has stopped touching another rigidbody/collider.
OnCollisionExit2D Sent when a collider on another object stops touching this object's collider (2D physics only).
OnCollisionStay :ref::OnCollisionStay is called once per frame for every collider/rigidbody that is touching rigidbody/collider.
OnCollisionStay2D Sent each frame where a collider on another object is touching this object's collider (2D physics only).
OnConnectedToServer Called on the client when you have successfully connected to a server.
OnControllerColliderHit OnControllerColliderHit is called when the controller hits a collider while performing a Move.
OnDestroy Destroying the attached Behaviour will result in the game or Scene receiving OnDestroy.
OnDisable This function is called when the behaviour becomes disabled.
OnDisconnectedFromServer Called on the client when the connection was lost or you disconnected from the server.
OnDrawGizmos Implement OnDrawGizmos if you want to draw gizmos that are also pickable and always drawn.
OnDrawGizmosSelected Implement OnDrawGizmosSelected to draw a gizmo if the object is selected.
OnEnable This function is called when the object becomes enabled and active.
OnFailedToConnect Called on the client when a connection attempt fails for some reason.
OnFailedToConnectToMasterServer Called on clients or servers when there is a problem connecting to the MasterServer.
OnGUI OnGUI is called for rendering and handling GUI events.
OnJointBreak Called when a joint attached to the same game object broke.
OnJointBreak2D Called when a Joint2D attached to the same game object breaks.
OnMasterServerEvent Called on clients or servers when reporting events from the MasterServer.
OnMouseDown OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider.
OnMouseDrag OnMouseDrag is called when the user has clicked on a GUIElement or Collider and is still holding down the mouse.
OnMouseEnter Called when the mouse enters the GUIElement or Collider.
OnMouseExit Called when the mouse is not any longer over the GUIElement or Collider.
OnMouseOver Called every frame while the mouse is over the GUIElement or Collider.
OnMouseUp OnMouseUp is called when the user has released the mouse button.
OnMouseUpAsButton OnMouseUpAsButton is only called when the mouse is released over the same GUIElement or Collider as it was pressed.
OnNetworkInstantiate Called on objects which have been network instantiated with Network.Instantiate.
OnParticleCollision OnParticleCollision is called when a particle hits a Collider.
OnParticleSystemStopped OnParticleSystemStopped is called when all particles in the system have died, and no new particles will be born. New particles cease to be created either after Stop is called, or when the duration property of a non-looping system has been exceeded.
OnParticleTrigger OnParticleTrigger is called when any particles in a particle system meet the conditions in the trigger module.
OnPlayerConnected Called on the server whenever a new player has successfully connected.
OnPlayerDisconnected Called on the server whenever a player disconnected from the server.
OnPostRender OnPostRender is called after a camera finished rendering the Scene.
OnPreCull OnPreCull is called before a camera culls the Scene.
OnPreRender OnPreRender is called before a camera starts rendering the Scene.
OnRenderImage OnRenderImage is called after all rendering is complete to render image.
OnRenderObject OnRenderObject is called after camera has rendered the Scene.
OnSerializeNetworkView Used to customize synchronization of variables in a script watched by a network view.
OnServerInitialized Called on the server whenever a Network.InitializeServer was invoked and has completed.
OnTransformChildrenChanged This function is called when the list of children of the transform of the GameObject has changed.
OnTransformParentChanged This function is called when the parent property of the transform of the GameObject has changed.
OnTriggerEnter OnTriggerEnter is called when the Collider other enters the trigger.
OnTriggerEnter2D Sent when another object enters a trigger collider attached to this object (2D physics only).
OnTriggerExit OnTriggerExit is called when the Collider other has stopped touching the trigger.
OnTriggerExit2D Sent when another object leaves a trigger collider attached to this object (2D physics only).
OnTriggerStay OnTriggerStay is called once per physics update for every Collider other that is touching the trigger.
OnTriggerStay2D Sent each frame where another object is within a trigger collider attached to this object (2D physics only).
OnValidate This function is called when the script is loaded or a value is changed in the inspector (Called in the editor only).
OnWillRenderObject OnWillRenderObject is called for each camera if the object is visible and not a UI element.
Reset Reset to default values.
Start Start is called on the frame when a script is enabled just before any of the Update methods are called the first time.
Update Update is called every frame, if the MonoBehaviour is enabled.

繼續閱讀