Daniel Lip
Daniel Lip

Reputation: 11341

How can I generate random cubes around specific point in random positions?

This script generate the random cubes in random positions but put them in general side place like a group and I want it to be spread more or less in all directions around the point.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Generate : MonoBehaviour
{
    public GameObject Prefab;
    [Range(1,50)]
    public int numberOfT;
    [Range(1,10)]
    public int numberOfPoints;

    // Start is called before the first frame update
    void Start()
    {
        GenerateT();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void GenerateT()
    {
        var parent = GameObject.Find("CLine");

        for (int i = 0; i < numberOfT; i++)
        {
            GameObject go = Instantiate(Prefab, parent.transform);
            go.transform.position = new Vector3(Random.Range(0, 50), Random.Range(0, 50), Random.Range(0, 50));
        }
    }
}

The object that should be the center point and the cubes should be generated around it is on the Plane at position 0,0,0

Depending on how you look at it but it looks like all the cubes are randomly created in the top right above the plane and the other directions are empty. I wanted to fill with random cubes for example 50 but that some of them will be also in the left side back forward directions.

Cubes seems like are all generated randomly as group in one area

Upvotes: 0

Views: 1296

Answers (1)

derHugo
derHugo

Reputation: 90872

If you want them around the center you probably rather would want to do

go.transform.position = new Vector3(Random.Range(-25f, 25f), Random.Range(-25f, 25f), Random.Range(-25f, 25f));

Make sure to use float values if you also are looking to get values like 1.3 instead of only int based position! Random.Range(0, 50) actually only returns full int values between 0 and 49.


If you want to spawn around the parent object and in the space coordinates of the parent (including its rotation and scale)

go.transform.localPosition = new Vector3(Random.Range(-25f, 25f), Random.Range(-25f, 25f), Random.Range(-25f, 25f));

Or if you rather want to spawn them around a second object

go.transform.position = otherObject.transform.position + new Vector3(Random.Range(-25f, 25f), Random.Range(-25f, 25f), Random.Range(-25f, 25f));

To the last thing: Spawn them only below and above the plane

A plane has a default size of 1x1 so we can simply use it's extensions like

// Here you define the max +- Y range in which to spawn cubes
[SerializeField] private float yRange = 1;

...

var planeTransform = plane.transform;
var planeScale = planeTransform.lossyScale;
go.transform.position = planeTransform.position + new Vector3(Random.Range(-planeScale.x, planeScale.x), Random.Range(-yRange, yRange), Random.Range(-planeScale.z, planeScale.z);

Upvotes: 2

Related Questions