访问用于武器的结构

时间:2015-03-06 12:08:16

标签: c# struct unity3d inventory

这是我在这里发表的第一篇文章,如果它有点令人困惑,请对不起。我也有阅读障碍,所以请原谅我的写作。

所以我试图做一个自上而下的RPG。我已经创建了一个结构来保存武器并使用了一个数组,所以我可以在检查器中填写它

我希望能够做的是从库存或其他东西传入id变量然后访问其他变量,如损坏和游戏对象

using UnityEngine;
using System.Collections;

[System.Serializable]
public struct Weapons {
    public string ID;
    public GameObject WeaponFront;
    public GameObject WeaponBack;
    public GameObject WeaponLeft;
    public GameObject WeaponRight;
    public float Damage;

}
public class WeaponHandler : MonoBehaviour {
    public Weapons[] Weapon;
}

所以我想像这样访问它

  hitobj.GetComponent<PhotonView>().RPC ("TakeDamage",PhotonTargets.All, /* damage from struct here */);

最好的方法是什么?我不确定我第一次使用结构

时我在做什么

玩家有4个游戏对象作为孩子这些是玩家面对不同方向的不同状态,每个都有武器图形,因此在结构中需要4个游戏对象,所以我可以激活正确的图形

我在考虑使用枚举 改变什么武器 使用,我可以创建一个枚举 持有所有不同的武器 当我用武器时,我可以 访问枚举和状态到 那个武器,取决于什么 国家被选中它选择相应的 武器处理程序中的id

这是我不确定怎么办我不知道 如何获取武器handeler的id

2 个答案:

答案 0 :(得分:0)

你的问题更多的是关于统一而不是结构,你的结构就像一个类,所以你需要一个武器类型的实际武器列表,以便你的命中对象获得被击中的武器的伤害。 / p> 如果没有看到你的所有代码,真的可以说在哪里击中你的命中对象的子弹对象有武器ID吗?你可以拥有所有武器的全球列表,然后用linq

查找你想要的武器
int id = hitobj.weaponId
float damage = globalWeapons.First(w=>w.id == id).Damage

答案 1 :(得分:0)

根据我对你的问题的理解,我试图用字典来保存Ids的武器结构。

以下是插图:

        Dictionary<String, Weapons> weaponsDico = new Dictionary<string, Weapons>();
        // Load the weapons for the given ID
        Weapons rambosArsenal = new Weapons();
        rambosArsenal.ID = "RAMBO";
        rambosArsenal.WeaponBack = new GameObject();
        // ....
        weaponsDico.Add("RAMBO", rambosArsenal);

        Weapons terminatorArsenal = new Weapons();
        terminatorArsenal.ID = "TERMINATOR";
        terminatorArsenal.WeaponFront = new GameObject();

        weaponsDico.Add(terminatorArsenal.ID, terminatorArsenal);


        String targetID = ""; // Put here an ID from which you want to get the weapons
        // In your other code
        Weapons targetWeapons =  new Weapons();
        Boolean existsTargetWeapons = weaponsDico.TryGetValue(targetID, out targetWeapons);
        if (existsTargetWeapons)
        {
            hitobj.GetComponent<PhotonView>().RPC ("TakeDamage",PhotonTargets.All, targetWeapons.Damage);
        }

除了使用TryGetValue,您还可以使用带有lambda表达式的扩展方法ad; @Ewan

相关问题