gpt4 book ai didi

c# - 通过检查器选择要引用的列表

转载 作者:太空宇宙 更新时间:2023-11-03 18:51:35 25 4
gpt4 key购买 nike

我有一个包含列表的非单一行为类,在编译时就固定好了。我有一些需要可重用的单一行为代码,它采用这些列表之一并对其进行修改。我希望能够通过检查员选择修改哪个列表,但我找不到一个好的谷歌答案来让我到达那里。

最好,我能够将列表添加到非单一行为,而无需修改负责选择列表的代码。

有什么建议吗?

要修改的列表示例:

[System.Serializable]
public class BOAT
{
public List<BlockScriptableObject> DefendInventory = new List<BlockScriptableObject>();
public List<BlockScriptableObject> AssistInventory = new List<BlockScriptableObject>();
public List<BlockScriptableObject> MiscInventory = new List<BlockScriptableObject>();
}

最佳答案

不推荐使用Reflection这里是其他人的建议!

反射总是很慢,尤其是当您要在框架的基础上访问和更改列表中的值时,这不是最好的主意。

类(class)的唯一(也是唯一)优势:(一旦您最终实现了所需的反射和额外的 EditorScript!)将为类中的每个列表自动填充选项。

巨大的缺点:每次 MonoBehaviour 需要此功能时,您都必须重复此操作并实现新的编辑器脚本。


您可以使用一个简单的 enum 和一个 Dictionary 来代替将相应的列表名称添加到 enum 和到 Dictionary 就像

[Serializable]
public class BOAT
{
public enum ListType
{
DefendInventory,
AssistInventory,
MiscInventory
}

public List<BlockScriptableObject> DefendInventory = new List<BlockScriptableObject>();
public List<BlockScriptableObject> AssistInventory = new List<BlockScriptableObject>();
public List<BlockScriptableObject> MiscInventory = new List<BlockScriptableObject>();

public Dictionary<ListType, List<BlockScriptableObject>> ListByType;

// Initialize the Dictionary in the default constructor
public BOAT()
{
ListByType = new Dictionary<ListType, List<BlockScriptableObject>>
{
{ListType.DefendInventory, DefendInventory},
{ListType.AssistInventory, AssistInventory},
{ListType.MiscInventory, MiscInventory}
};
}
}

然后为了访问和更改特定列表,您可以通过脚本中的检查器设置枚举类型

// gives you a Dropdown for available ListType values
// in the Inspector
public BOAT.ListType listToChange;

...

var listToBeChanged = someBoat.ListByType[listToChange];

使用它,Inspector 会自动为您处理所有事情,它可以在编辑器中和运行时运行,无需任何额外开销。


小演示代码

public class blarf : MonoBehaviour
{
public BOAT.ListType listToChange;
public BOAT boat;

public List<BlockScriptableObject> currentList;

// only for the demo (later you would rather do this in a Property)
// update the current accessed and changed list according to the
// selected ListType
private void Update()
{
currentList = boat.ListByType[listToChange];
}
}

enter image description here

关于c# - 通过检查器选择要引用的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56938609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com