有没有办法创建列表或将列表重命名,例如从 tempList 到 Collection1?
不!
这将是什么用例?用户不编写/读取/关心代码......作为开发人员的你......之后你的代码被编译并且你不只是在运行时扩展编译的代码;)
听起来您想要使用的是Dictionary<string, List<int>>,因此您可以通过string 键名来寻址不同的列表,例如
private Dictionary<string, List<int>> _lists = new Dictionary<string, List<int>>();
// list is optional => if you already have a list you want to register pass it in
// if only a string is passed in a new list is automatically created
public void AddList(string keyName, List<int> list = null)
{
if(_lists.ContainsKey(keyName))
{
Debug.LogError($"Already contains a list with key name {keyName}", this);
return;
}
if(list == null) list = new List<int>();
_lists.Add(keyName, list);
}
public List<int> GetList(string keyName)
{
if(!_lists.ContainsKey(keyName))
{
Debug.LogError($"Does not contain a list with key name {keyName}", this);
return null;
}
return _lists[keyName];
}
// or alternatively
public bool TryGetList(string keyName, out List<int> list)
{
return _lists.TryGetValue(keyName);
}
public void RemoveList(string keyName)
{
if(!_lists.ContainsKey(keyName))
{
Debug.LogError($"Does not contain a list with key name {keyName}", this);
return null;
}
_lists.Remove(keyName);
}
现在 IF 的“用户”实际上是指开发人员在 Unity 中使用您的脚本,它可能会变得更复杂一些,但您可以执行类似的操作
[Serializable]
public class ListEntry
{
public string Name;
public List<int> Values;
}
// Edit via the Inspector in Unity
public ListEntry[] lists;
然后您可以通过 Inspector 简单地添加和命名您的列表。
然后我仍然会在运行时使用之前的代码(或类似的代码),并使用检查器中的值创建字典一次,例如
private void Awake()
{
foreach(var list in lists)
{
_lists.Add(list.Name, list.Values);
}
}
当然你可以/应该实现一些东西来确保所有列表名称都是唯一的。在OnValidate 或自定义编辑器脚本中......但我认为这有点超出了这个问题的范围;)