Doubt with code - Linear Distribution in Script

Hello everyone!

I have a doubt with the following question

In Unity, you can select several objects at once, and in the Inspector you can set L(8, -8) to the X position. This makes the objects arrange themselves perfectly between those two points.

Is there any way to do this in code?

For example I have four objects that have the same parent, could I select them and perform this action by code?
I ask this in case there is a simple way to do it.

Thank you very much for your time

I assume you’re asking if there is a way via script that you can just call a method that you pass the string “L(8, -8)” to and get the same result?

Considering that I only just learned today that this even is a thing in Unity. Nope… I don’t know of a way to do that via code. Maybe there is? But I wouldn’t be surprised if it’s not available.

…

If you want a way to just position them along a line… you could just do this:

static IEnumerable<float> LinearDistribution(float min, float max, int count)
{
    if (count <= 1)
    {
        yield return return Mathf.Lerp(min, max, 0.5f);
        yield break;
    }

    float delta = 1f / (count - 1);
    for (int i = 0; i < count; i++)
    {
        yield return Mathf.Lerp(min, max, delta * (count - 1));
    }
}

var objs = *get some transforms*;
int i = 0;
foreach (var x in LinearDistribution(-8f, 8f, objs.Length))
{
    var pos = objs[i].position;
    pos.x = x;
    objs[i].position = pos;
    i++;
}

To put it another way, you can write a script to figure out N equally-spaced positions between -8 and 8 (or any other values), but your code has to do all of the math itself.

For example, -8 to 8 is a range of 16. The script needs to have something like range=last-first; to get that. To get the spacing, you have to realize that a point is on each end, so if you have 5 points there are 3 in the middle, which divides the range into 4 parts, so the size of the gap between points is range/(pointCount-1). That has to be in the script. Then they need to be placed using: first+gap*pointNumber (pointNumber goes from 0 to one less than the # of points to place). That’s not difficult math – it’s 7th-grade algebra at best – and it can be turned into a function (by you) where you give it first, last and pointCount and it spits out an array of the values. That makes it feel built-in and makes it so you can easily use it after you’ve forgotten exactly how the equations work.

Thank you very much Lord and Owen. I was looking on the internet to see if there was a “native” way but nothing.

So I have found the solution by putting into practice what you both have told me. I have a List with the objects, so I make a coroutine to which I pass the List that I go through and with mathematical calculations I place them.

And really, thank you very much for your time.