如何组织嵌套类作为Unity中的引用?

问题描述 投票:1回答:1

所以我正在开发一款游戏,我想要一些关于如何在Unity中对项目进行排序以便简单易读的编码参考的建议。我知道我目前的方法存在缺陷,我真的只是喜欢一些指导。

所以我正在做的是使用类来分隔项目类别及其项目。例如,这里是一个脚本设置的想法:

public class Items {
    public class Equipment {
        public class Weapons {
            public Item Sword = new Item();
            Sword.name = "Sword";
            Sword.cost = 1;
        }
    }
}

然后是一个基本的Item类

public class Item {
    public string name;
    public int cost;
}

我可以说这是一种可怕的做法,尤其是基于我一直遇到的问题,但我喜欢使用像Items.Equipment.Weapons.Sword这样的引用的想法,我已经习惯于使用我之前的API用过的。

我愿意完全改变一切,我只是想要一些提示。谢谢。

我想我的主要问题是(是),组织嵌套类的最佳方法是什么,以便它们可以轻松地从其他脚本引用?

我找到的答案是,在我的情况下,不是嵌套类,而是使用命名空间将项目分成类别。太感谢了。

c# unity3d scripting items
1个回答
4
投票

我建议使用ScriptableObjects来创建你的物品,装甲和武器。 You'll have to spend an hour or two learning them,但是我觉得如果你走那条路,你的设计会更开心。

将ScriptableObject视为一组属性(项目名称,成本,攻击强度,防御能力等)。对于游戏中的每个项目,您可以创建ScriptableObject的实例。那些ScriptableObject实例然后成为Unity项目中的资源,就像预制件或精灵一样。这意味着您可以在项目中拖动它们,并将它们分配给MonoBehaviours上的字段。这将导致您可以通过将设备从“项目”视图拖动到“检查器”中来将设备分配给角色。

这是一个看起来如何的例子

Item.cs

public class Item : ScriptableObject
{
    public string name;
    public int cost;
    public Sprite image;
}

Equipment.cs

public class Equipment : Item
{
    public Slots slot;
}

public enum Slots
{
    Body,
    DoubleHanded,
    Hands,
    Head,
    Feet,
    Legs,
    LeftHand,
    RightHand
}

Weapon.cs

// CreateAssetMenu is what lets you create an instance of a Weapon in your Project
// view.  Make a folder for your weapons, then right click inside that folder (in the 
// Unity project view) and there should be a menu option for Equipment -> Create Weapon
[CreateAssetMenu(menuName = "Equipment/Create Weapon")]
public class Weapon : Equipment
{
    public int attackPower;    
    public int attackSpeed;
    public WeaponTypes weaponType;
}

public enum WeaponTypes
{
    Axe,
    Bow,
    Sword
}

Armor.cs

[CreateAssetMenu(menuName = "Equipment/Create Armor")]
public class Armor : Equipment
{
    public int defensePower;
}

现在在你的项目中创造一堆武器和盔甲。

enter image description here

使ScriptableObjects更好的一件事是你可以在你的Inspector中编辑它们,而不是必须通过代码来完成它(尽管你也可以这样做)。

enter image description here

现在,在你的“角色”MonoBehaviour上,为该角色的装备添加一些属性。

public class Character : MonoBehaviour
{
    public Armor bodyArmor;
    public Armor headArmor;
    public Weapon weapon;
}

现在,您可以在检查器中将武器和护甲分配给角色

enter image description here

您可能想要比我的示例更符合您需求的东西,但这些是基础知识。我建议花些时间查看ScriptableObjects。阅读我之前链接的Unity文档,或在YouTube上观看一些视频。

Unity的优势之一是它允许您通过编辑器而不是通过代码进行大量的设计和配置,ScriptableObjects强化了这一点。

© www.soinside.com 2019 - 2024. All rights reserved.