Unet下

版权声明:转载 请说明 https://blog.csdn.net/qq2512667/article/details/82819415
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)。

要在服务器端生成的物品 都要加上 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

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.

猜你喜欢

转载自blog.csdn.net/qq2512667/article/details/82819415