Why do my first 50 instances of a prefab have the same properties?
I have been trying to create instances of a prefab in my game and then randomly changing the GameObject's children objects that are created. The prefab is instantiated no issue, when I go to edit the GameObject that was created, all 50 are updated (at least they all come out the same after executing the code.). This only occurs when these 50 game objects are created at the same time. If they are done frame by frame, there is no issue.
//Generate platforms
for (int i = meshPlatforms.Length; i < platformsToGenerate; i++)
{
//Get the last game object position and figure out the new position.
GameObject loopPlatform = meshPlatforms[i - 1];
platformPosition = loopPlatform.transform.position + meshTransform;
//Create a new platform tile
Array.Resize(ref meshPlatforms, i + 1);
GameObject newPlat = Instantiate(tilePrefab, platformPosition, tilePrefab.transform.rotation);
newPlat.gameObject.tag = slopeChildrenTag;
newPlat.transform.parent = slopeSet.transform;
GeneratePlatform(ref newPlat);
meshPlatforms[i] = newPlat;
}
//Update Distance Reader
GameObject textBox = GameObject.FindGameObjectWithTag(distanceBoxTag);
TextMesh distanceBox = (TextMesh)textBox.GetComponent("TextMesh");
distanceBox.text = String.Concat("Distance: ", (Math.Round(Math.Abs(player.transform.position.z))).ToString());
}
//This method will do the heavy lifting for running our algorithms to generate wood platforms, sun spots,
//and regens.
void GeneratePlatform(ref GameObject platform)
{
Transform[] allChildren = platform.GetComponentsInChildren<Transform>(true);
int isObjectActive = 2;
System.Random random = new System.Random();
foreach (Transform platformComponent in allChildren)
{
if (platformComponent.tag.Equals(woodPileTag, StringComparison.OrdinalIgnoreCase))
{
platformComponent.gameObject.SetActive(true);
//woodPileAlgorithm
if (random.Next(1, woodPileOdds) != isObjectActive)
{
platformComponent.gameObject.SetActive(false);
}
}
else if (platformComponent.tag.Equals(spotLightTags, StringComparison.OrdinalIgnoreCase))
{
platformComponent.gameObject.SetActive(true);
//spot light algorithm
if (random.Next(1, lightSpotOdds) != isObjectActive)
{
platformComponent.gameObject.SetActive(false);
}
}
//else do nothing
}
}
I just want the first 50 to be generated the same way the following ones are generated. Not sure if the instance is causing issues or if I am actually changing the prefab. Any tips or places to look are helpful, I have been doing research for about two days now.
Answer by MrWalbert · May 21, 2020 at 06:19 PM
Just to follow up, the platforms are all created and spaced correctly, but when I pass the game object into GeneratePlatform, they are all affected the same way.
So I think I found a fix. It was the random number generator. https://stackoverflow.com/questions/8948819/how-do-i-make-my-c-sharp-random-number-generator-change-with-each-time-the-const