微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 [Command] 将游戏对象从客户端发送到服务器

如何解决使用 [Command] 将游戏对象从客户端发送到服务器

这真的可能吗?

我在命令中将单个值发送回服务器没有问题,但我无法将它们打包成一个游戏对象(具有网络标识),然后将其作为参数发送到命令中。

通过 Mirror 文档应该是可能的,我已经尝试按照这个例子进行操作:

class Item 
{
    public string name;
}

class Weapon : Item
{
    public int hitPoints;
}

class Armor : Item
{
    public int hitPoints;
    public int level;
}

class Player : NetworkBehavIoUr
{
    [Command]
    void CmdEquip(Item item)
    {
        // IMPORTANT: this does not work. Mirror will pass you an object of type item
        // even if you pass a weapon or an armor.
        if (item is Weapon weapon)
        {
            // The item is a weapon,// maybe you need to equip it in the hand
        }
        else if (item is Armor armor)
        {
            // you might want to equip armor in the body
        }
    }

    [Command]
    void CmdEquipArmor(Armor armor)
    {
        // IMPORTANT: this does not work either,you will receive an armor,but 
        // the armor will not have a valid Item.name,even if you passed an armor with name
    }
}

但我没有运气,在服务器上,而不是我传递的对象,服务器有自己的副本和自己的值。

知道我哪里出错了吗?

解决方法

它在文档中说“此代码无法立即使用。”。 从文档: 如果您为 Item 类型提供自定义序列化程序,则 CmdEquip 将起作用。 例如:

public static class ItemSerializer 
{
    const byte WEAPON = 1;
    const byte ARMOR = 2;

    public static void WriteItem(this NetworkWriter writer,Item item)
    {
        if (item is Weapon weapon)
        {
            writer.WriteByte(WEAPON);
            writer.WriteString(weapon.name);
            writer.WritePackedInt32(weapon.hitPoints);
        }
        else if (item is Armor armor)
        {
            writer.WriteByte(ARMOR);
            writer.WriteString(armor.name);
            writer.WritePackedInt32(armor.hitPoints);
            writer.WritePackedInt32(armor.level);
        }
    }

    public static Item ReadItem(this NetworkReader reader)
    {
        byte type = reader.ReadByte();
        switch(type)
        {
            case WEAPON:
                return new Weapon
                {
                    name = reader.ReadString(),hitPoints = reader.ReadPackedInt32()
                };
            case ARMOR:
                return new Armor
                {
                    name = reader.ReadString(),hitPoints = reader.ReadPackedInt32(),level = reader.ReadPackedInt32()
                };
            default:
                throw new Exception($"Invalid weapon type {type}");
        }
    }
}

所以似乎您需要在客户端和服务器之间传递序列化信息而不是原始类型才能使其工作。以防万一您没有考虑到这一点。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。