I made this code to load about 8 different textures to a list of objects with a texture property.
I have a folder with textures named “1.png, 2.png, 3.png,…….,46.png” and I want the 8 different objects to be loaded with randomly chosen textures.
DockedFruitsList = new List<Fruit>(8);
for (int i = 0; i < 8; i++)
{
Fruit temp = new Fruit();
temp = new Fruit();
temp.Position = AvailablePositions[i];
int random=(new Random().Next(0, 4600) % 46);
temp.Texture = Content.Load<Texture2D>(@"Fruits/" + random);
DockedFruitsList.Add(temp);
}
The thing is, despite the random always generates a different number, the result of draw is always the same texture, it changes from a run to another run, but it’s always the same for all the 8 textures
spriteBatch.Begin();
for (int i = 0; i < DockedFruitsList.Count; i++)
{
spriteBatch.Draw(DockedFruitsList[i].Texture, DockedFruitsList[i].Position, Color.White);
}
spriteBatch.End();
Try this out:
Odds are you’ll get an output like this:
This is because the seed of the
Randomclass is initialized with a time-based value. If you initialize many instances of theRandomclass near the same point in time, then they will all end up with the same seed, and so the values they will produce will all be the same.What you really want to do is to create one
Randominstance and use that for all your random values. The values generated will have no relation to each other:Output: