0

我目前正在学习统一制作多人 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)
{

}
}

在手柄射击中,我得到装备的武器并检查它的类型,并根据类型调用射击这种类型的方法。就我而言,它正在投掷武器。在投掷武器函数中,我实例化武器预制件,然后调用CmdOnWeaponThrowed在所有客户端中生成对象。所以我的问题是我无法访问 CmdOnWeaponThrowed 函数中的 throwedObject 变量,因为命令不会将对象作为参数访问。

我得到的错误

4

1 回答 1

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);
}

希望这可以帮助 :)

于 2017-12-11T12:02:46.747 回答