Seperate scripts for prefab objects?
Hi all. I have created four objects from a single prefab, which has the following script on it:
using UnityEngine;
using System.Collections;
public class Treescript : MonoBehaviour
{
public int amount;
public int randomWood ()
{
System.Random num = new System.Random();
int c = num.Next(1, 4);
return c;
}
// Use this for initialization
void Start()
{
int rand = randomWood();
if (rand == 1)
{
amount = 50;
}
else if (rand == 2)
{
amount = 100;
}
else if (rand == 3)
{
amount = 150;
}
print("Wood amount: " + amount);
}
// Update is called once per frame
void Update()
{
}
}
The problem i'm getting is that all four objects get the same randomly generated number every time (apart from some strange circumstance where one is different). How do i fix this? Cheers,
Answer by Desoxi · Nov 21, 2016 at 01:57 PM
Do you instantiate the prefabs per code or are they all present at the start of your scene? It looks like they are all using the same random seed to generate the random number. And maybe, when they are all in your scene already the method is called at the same time. Im not sure though. Did you try using the unity Random class? Heres the link: https://docs.unity3d.com/ScriptReference/Random.html
Answer by Emolk · Nov 21, 2016 at 02:14 PM
It seems to have fixed it.
Though it is still very strange. There seems to be rolls in where amount won't change at all, for example 4 or 5 rolls in a row where amount will stay at the same variable for one object. i'm not sure how random the random class is?
public int randomWood()
{
int c = Random.Range(1, 4);
// System.Random num = new System.Random();
// int b = Mathf.num(1, 3);
// int c = num.Next(1, 4);
return c;
}
Hm, you could use Random.value too and just multiply it by 4 to get a random number between 1 and 4. And then you would have to floor it with $$anonymous$$athf.Floor or $$anonymous$$athf.FloorToInt. $$anonymous$$aybe that is more random? :D