Tony - 2 months ago 32

C# Question

I'm currently instantiating some objects in a row using

`Vector3.Lerp`

Code is:

`Vector3 startPosition= blah.transform.position.`

Vector3 endPosition = getCurrentMousePosition();

Vector3 size = ObjectToSpawn.GetComponent<Renderer>().bounds.size;

fillCount = Mathf.RoundToInt(Vector3.Distance(startPosition, endPosition) / size.z);

float distance = 1.0f / fillCount;

float lerpValue = 0;

for (int i = 0; i < fillCount; i++)

{

lerpValue += distance;

nextPosition = Vector3.Lerp(startPosition, endPosition, lerpValue);

Instantiate(ObjectToSpawn, nextPosition, Quaternion.identify);

}

Part of me thinks that it might just be worth trying to instantiate the objects in a row just based on their size / distance, but I can't seem to get that quite right either. Although this system is being used for something else, and I'd rather not rewrite entirely new code, if this can be modified slightly to work. I'm guessing that rounding the Lerp value would be the way to go, possibly?

Any input or advice would be greatly appreciated.

Answer Source

If you want the objects to exactly touch with no gaps, the distance between the start and end positions has to be an integer multiple of their size.

Try adding the following line just before your loop:

```
endPosition = Vector3.Lerp(startPosition, endPosition, (fillCount * size.z) / Vector3.Distance(startPosition, endPosition));
```