|
-
May 7th, 2012, 01:46 PM
#1
Random array element gets value changed with variable
Hi all,
I'm making a roguelike RPG in VS 2008, XNA Studio 3.0.
In the function that follows, I take a random element from an array (the master list of items, iM) and put it into a variable. The array is of type Item, an inherited class I created for all the different kinds of items. Each Item initially has a startingPos of (0,0), and they're supposed to be given a random startingPos before they're added to the mapItems.
Code:
public void CreateItems(ref List<Item> iM)
{
Random r = new Random();
for (int it = 0; it < maxMapItems; it++)
{
int tmpR = r.Next(0, iM.Count);
Item tmpItem = iM[tmpR];
//set starting position for the item on the current map
tmpItem.setStartingP( new Vector2((float)r.Next(4, maxTilesH - 4), (float)r.Next(4, maxTilesV - 4)));
if (tmpItem.getStartingP() == player.startingPos || tileArray[(int)tmpItem.getStartingP().X, (int)tmpItem.getStartingP().Y].isSolid)
{
it--;
continue;
}
mapItems.Add(tmpItem);
//if the map has a shop, populate it with items
}
if (curMap.isShopMap)
{
Item tmpShopItem = new Item();
foreach (Tile t in tileArray)
if (t.name == "floor")
{
tmpShopItem = iM[r.Next(0, iM.Count)];
tmpShopItem.setStartingP(t.absPos);
//new Potion(potionTexture, potionNames[r.Next(0,
//potionNames.Count())] + " potion", t.absPos.X, t.absPos.Y);
mapItems.Add(tmpShopItem);
}
}
return;
}
The problem is hard to explain. Essentially, after the line
Code:
Item tmpItem = iM[tmpR];
, the array element somehow has its value changed, with the startingPos becoming tmpItem's startingPos. It's as if the new Item is just pointing to the same object. So when the map has a shop, the items just pile on top of each other, because they have the same startingPos.
I noticed that when I created objects of a subclass of Item (in the above code, Potions) and filled the shop with them, they were in the right place. So it's not the logic, but something in the memory screwing things up.
Any ideas? Thanks so much to anyone who can help me.
Katie
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|