我是 C# 的新手,所以如果我问的是愚蠢的问题或者我的问题不正确,请原谅。
这是我的代码:
using UnityEngine;
using System;
namespace DuloGames.UI
{
[Serializable]
public class UISpellInfo
{
public int ID;
public string Name;
public Sprite Icon;
public string Description;
public float Range;
public float Cooldown;
public float CastTime;
public float PowerCost;
public float test;
[BitMask(typeof(UISpellInfo_Flags))]
public UISpellInfo_Flags Flags;
}
}
这是我的 UIspellDatabase
类:
using UnityEngine;
namespace DuloGames.UI
{
public class UISpellDatabase : ScriptableObject {
#region singleton
private static UISpellDatabase m_Instance;
public static UISpellDatabase Instance
{
get
{
if (m_Instance == null)
m_Instance = Resources.Load("Databases/SpellDatabase") as UISpellDatabase;
return m_Instance;
}
}
#endregion
public UISpellInfo[] spells;
/// <summary>
/// Get the specified SpellInfo by index.
/// </summary>
/// <param name="index">Index.</param>
public UISpellInfo Get(int index)
{
return (spells[index]);
}
/// <summary>
/// Gets the specified SpellInfo by ID.
/// </summary>
/// <returns>The SpellInfo or NULL if not found.</returns>
/// <param name="ID">The spell ID.</param>
public UISpellInfo GetByID(int ID)
{
for (int i = 0; i < this.spells.Length; i++)
{
if (this.spells[i].ID == ID)
return this.spells[i];
}
return null;
}
}
}
下面是我如何获取 UISpellInfo
的现有实例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using WorldServer;
using Spells;
using DuloGames.UI;
public class Character : MonoBehaviour
{
private void SeeAllInstances()
{
foreach (var item in UISpellDatabase.Instance.spells)
{
Debug.Log("ID->" + item.ID + " name: " + item.Name);
}
}
我可以清楚地看到这个类 UISpellInfo
的所有实例。
我想要实现的只是向数组 UISpellInfo[] spells;
添加更多实例。
据我所知,UISpellInfo
类的所有实例都在此处加载 UISpellInfo[] spells;
然后我在 SeeAllInstances() 中执行的 foreach
我可以看到所有实例和每个实例的数据。
如果我问得正确,我的问题是如何在 UISpellInfo[] spells;
中添加更多实例?
有人可以帮我解决这个问题吗?
最佳答案
我认为你需要使用 List<T>
对于您的场景,作为 Array
声明了一个大小,我们必须在添加删除元素时进行跟踪,以了解其中有多少元素以及哪些槽有值,以便我们可以在最后一个可用索引处添加新项目。
对于我们事先不知道元素数量的情况List<T>
是一个更好的选择,如果您正在使用它,那么您只需要调用 Add()
在您的实例上添加新项目的方法。
你的代码在那种情况下会是这样的:
public List<UISpellInfo> spells;
这将包含 UISpellInfo
类型的所有项目现在在你的代码中的某个地方,你可以像下面这样添加:
UISpellDatabase.Instance.spells.Add(new UISpellInfo());
关于C# - 将类的新实例添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49435760/