use*_*755 2 c# xna list outofrangeexception
我正在制作农场/塔防游戏,我在编程时非常新.我似乎在XNA中使用Lists <>或数组时遇到了一个主要问题.我无法让它从列表中返回我想要的索引.
主要问题是我的种植引擎.我已经成功实施了种植系统,可以生成具有不同属性的植物(精灵对象)列表并将它们放在地图上.现在,我需要一种方法来访问工厂列表中的特定工厂,基于鼠标点击该工厂.我觉得我非常接近,但最终我得到了一个无法解决的ArgumentOutOfRangeException.以下是代码的演练:
初始化
public void Addplants()
{
switch (Mode)
{
case "Wotalemon":
NewPlant = new Plant(Texture, msRect);
NewPlant.AddAnimation("seed", 0, 16, 64, 64, 1, 0.1f);
NewPlant.AddAnimation("sprout", 64, 16, 64, 64, 1, 0.1f);
NewPlant.AddAnimation("wota", 128, 16, 64, 64, 1, 1.0f);
NewPlant.CurrentAnimation = "seed";
NewPlant.DrawOffset = new Vector2(32, 48);
NewPlant.Position = Position;
NewPlant.Type = "wotalemon";
NewPlant.Birthday = Days;
NewPlant.IsSelected = false;
plants.Add(NewPlant);
thisPlant = NewPlant;
//various plants after this
Run Code Online (Sandbox Code Playgroud)
更新/绘图
我使用一些简单的foreach循环来更新和绘制植物,这里没有问题.
GetInfo(此方法使用spriteobject的hitbox属性和mouseRectangle)
public void GetInfo(Rectangle ms)
{
msRect = ms;
for (int i = 0; i < plants.Count; i++)
{
foreach (Plant NewPlant in plants)
{
if (NewPlant.BoundingBox.Intersects(msRect))
{
SelectedIndex = i;
NewPlant.Tint = Color.Black;
}
else
NewPlant.Tint = Color.White;
}
}
}
Run Code Online (Sandbox Code Playgroud)
最后,这是问题所在:
public void SelectPlant()
{
//if (SelectedIndex != null)
if (SelectedIndex > plants.Count | SelectedIndex < 0)
SelectedIndex = plants.Count;
SelectedPlant = plants[SelectedIndex];
}
Run Code Online (Sandbox Code Playgroud)
此行中抛出异常:
SelectedPlant = plants[SelectedIndex];
Run Code Online (Sandbox Code Playgroud)
调试器将值显示为0.我尝试了各种方法来尝试防止索引为空.我觉得Getinfo()方法中的一些东西是关键.我确信我非常接近成功,因为我在那里插入的颜色测试非常有效.当鼠标悬停在植物上时,它会变黑,当我移除鼠标时,它会恢复正常.
这完全是我想要的行为类型,除了我希望它将selectedIndex设置为我正在调整的工厂的索引.任何建议将不胜感激.
首先使它成为一个正确的或||检查>= plants.Count- 记住列表的索引是0.然后按照建议将其设置为计数 - 1:
if (SelectedIndex >= plants.Count || SelectedIndex < 0)
SelectedIndex = plants.Count - 1
Run Code Online (Sandbox Code Playgroud)