Reputation: 758
I have this code to set random x and z coordinates for several game objects:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class SetPositions : MonoBehaviour
{
// Use this for initialization
void Start ()
{
System.Random rnd = new System.Random();
int a = rnd.Next (-9,9);
int b = rnd.Next(-9,9);
transform.position = new Vector3(a, transform.position.y, b);
}
}
When I use this script with multiple game objects, mot of them end up in the exact same location. I have gathered that this has something to do with the time being used, but how to I make sure all of the objects are in different positions? Is there a workaround to generate the random numbers at different times, or should the code be moved around/changed?
Upvotes: 1
Views: 158
Reputation: 758
Thanks to Scott Chamberlain's comment, I was able to find the Unity Documentation for random numbers and solve my problem. UnityEngine.Random evidently does not use the time and so random positions are different from each other. Here is the correct script:
using UnityEngine;
using System.Collections;
public class SetPositions : MonoBehaviour
{
public GameObject PickUp;
void Start()
{
transform.position = new Vector3(Random.Range(-9.5f, 9.5f), 0.5f, Random.Range(-9.5f, 9.5f));
}
}
PickUp is a prefab that I use for all of the pickup objects.
Upvotes: 0
Reputation: 5707
You may need Random.insideUnitCircle
var rndPoint = (Random.insideUnitCircle * 9);
transform.position = new Vector3(rndPoint.x, transform.position.y, rndPoint.y);
var rndPoint = (Random.insideUnitSphere * 9);
rndPoint.y = transform.position.y;
transform.position = rndPoint;
Upvotes: 1