我目前正在学习制作多人fps,但我遇到了问题。我有一个PlayerShoot
脚本,可以处理不同的武器和类型。这是代码。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using Weapons;
public class PlayerShoot : NetworkBehaviour {
public WeaponManager weaponManager;
void Awake()
{
weaponManager = GetComponent<WeaponManager> ();
if (weaponManager == null)
return;
}
void Update()
{
if (!isLocalPlayer)
return;
// Fire
if (Input.GetButtonDown ("Fire1"))
{
HandleFire ();
}
}
void HandleFire()
{
Weapon currentWeapon = weaponManager.equippedWeapon;
if (!currentWeapon.CanFire())
return;
switch (currentWeapon.weaponType)
{
case WeaponType.THROWING:
ThrowWeapon ((WeaponThrowing)currentWeapon);
break;
case WeaponType.FIREARM:
RaycastShoot(currentWeapon);
break;
case WeaponType.MELEE:
AttackMelee(currentWeapon);
break;
}
}
// Throwing weapon
void ThrowWeapon(WeaponThrowing weapon)
{
GameObject throwedObject = (GameObject)Instantiate (weapon.throwObjectPrefab, weaponManager.throwWeaponPlace.position, weaponManager.throwWeaponPlace.rotation);
Debug.Log(throwedObject);
Rigidbody throwedObjectRB = throwedObject.GetComponent<Rigidbody> ();
if (throwedObjectRB != null)
{
throwedObjectRB.AddForce(throwedObject.transform.forward * weapon.throwForce, ForceMode.Impulse);
}
CmdOnWeaponThrowed();
}
[Command]
void CmdOnWeaponThrowed()
{
// How to access my throwed object here.
NetworkServer.Spawn(obj, obj.GetComponent<NetworkIdentity>().assetId);
}
// Raycast shooting
void RaycastShoot(Weapon weapon)
{
}
// Melle attack
void AttackMelee(Weapon weapon)
{
}
}
在手柄火中我得到装备好的武器并检查其类型并根据类型I调用此类型的方法。在我的情况下,它是扔武器。在throw武器功能中,我实例化武器预制,然后调用CmdOnWeaponThrowed
在所有客户端中生成对象。所以我的问题是我无法访问CmdOnWeaponThrowed函数中的throwedObject变量导致命令不能将对象作为参数访问。
答案 0 :(得分:0)
将其传递给方法:
[Command]
void CmdOnWeaponThrowed(GameObject obj)
{
var netId = obj.GetComponent<NetworkIdentity>();
if (netId == null)
{
// component is missing.
return;
}
NetworkServer.Spawn(obj, netId.assetId);
}
然后
void ThrowWeapon(WeaponThrowing weapon)
{
GameObject throwedObject = (GameObject)Instantiate (weapon.throwObjectPrefab, weaponManager.throwWeaponPlace.position, weaponManager.throwWeaponPlace.rotation);
Debug.Log(throwedObject);
Rigidbody throwedObjectRB = throwedObject.GetComponent<Rigidbody> ();
if (throwedObjectRB != null)
{
throwedObjectRB.AddForce(throwedObject.transform.forward * weapon.throwForce, ForceMode.Impulse);
}
CmdOnWeaponThrowed(throwedObject);
}
希望这会有所帮助:)