How to account for RNG when multiple GameObjects are using the same script?
Hey, so this is a bit of an odd question. I am making a game, think of it as a sort of pet simulator where you take care of a little guy and he has stats and stuff. I have a script I use that controls all of his behavior, and there is some RNG stuff involved where it decides what action he does next and what direction he walks and stuff like that (I am using System.Random for this). The issue arises when I want to have multiple of these "pets" in the scene. If I have them both using the same controller script, then the RNG causes them all to do the same actions and move in the same ways. Obviously I can't make a new script for every different pet I want to have active in the scene, so is there any way to cause them to roll different numbers while still using the same script? And that isn't really even accounting for some other issues it'll have, for example, I am saving the stats of the pet in player prefs like "Speed", "Hunger", etc. If I instantiate a second pet and call for the same stats then both of them will just have all of the same stuff. I think I can get around this somehow using unique IDs or something, but I have no idea where I would even start with the first issue. So if anyone has any idea on how I would go about solving either of these issues, please let me know. Also if you need any code then let me know, but I just don't think any is necessary for this.
Answer by lgarczyn · Dec 24, 2019 at 12:08 AM
You need to "seed" the randomness generator. Unity solves that problem by having everything share the same random number generator, using the Random class.
However System.Random allows you to have independent seeds that are all initialized to the current time in seconds, and therefore will give the same sequence of points.
You can simply use UnityEngine.Random, or use something new System.Random((int)(Time.time) + sceneNumber * 10000)
Thank you! Now I just need to figure out how to save the different values in different spots in the player prefs...
Your answer
Follow this Question
Related Questions
Bullet not moving rigidbody2d,AddForce not working for bullet 1 Answer
Giving different values to cloned prefabs with the same script. 1 Answer
Delete prefab clone when collided with the player, Unity 2D 1 Answer
Instantiate not spawning at correct position 1 Answer
Sprites assigned to prefab' script' fields not assigned after launch 0 Answers