Question by
Lady_Saturday · Aug 08, 2020 at 09:18 PM ·
c#2drandom.rangerandomspawning
Two objects sharing a script should spawn different random objects, but instead they spawn the same random object.
I have two "customer" objects that share an Order Manager script. Ideally, every time a customer needs to create a new order, it should be different than the last one. What happens instead is that customer 1 orders X and Y, and then customer 2 will order X and Y instead of Z (or whichever different combination). When the script is placed on just one customer instead of 2, the random order function works correctly. There are no static variables.
This is the method that's causing an issue:
IEnumerator CustomerOrder(bool status, float delayTime)
{
yield return new WaitForSeconds(delayTime);//delay between orders
imageOffset.y = -0.75f;//space between order visuals
numberOfOrderItems = rnd.Next(1, maxOrderNumber + 1);//between 1 and 3 items per order
customerOrders = new GameObject[numberOfOrderItems];// order collection
Instantiate(orderBackgrounds[numberOfOrderItems - 1], orderVisual.transform);//Spawn correct background for number of items
for (int x = 0; x < numberOfOrderItems; x++)
{
int y = rnd.Next(products.Length);//choose a random number representing an index in the products array
customerOrders[x] = Instantiate(productImages[y],
orderVisual.transform.position + imageOffset,
Quaternion.identity,
orderVisual.transform);//spawn a visual representation of the order
imageOffset.y += -0.95f;//places next order visual lower
}
makingOrder = false;//we've finished making the order
}
Comment
Best Answer
Answer by Lady_Saturday · Aug 08, 2020 at 10:00 PM
I feel really silly. I was able to fix this issue by adding one line to the beginning of the method:
rnd = new System.Random();
I'm not certain if this is really the best way, but it seems to work.