Consistent spacing between gameobjects when some disabled
First of all, I'm new to this forum so apologies to any mods if I've done anything wrong. I am looking for a way to keep gameobjects equally spaced if one is removed in a line of them.
The best way to picture this question:
Let x be multiple game objects, cubes for example
x x x x x
Say I set the middle x active to false, currently this happens (obviously):
x x x x
What I want to do is keep the spacing between the objects consistent, so when an x is removed, the others adapt and adjust accordingly, for example, when the middle x is deactivated:
x x x x x
to
x x x x
I know this is really poorly worded but im looking for a reasonably simple quick way to achieve this.
Things to keep in mind:
I want them to adjust no matter which x is removed
Also another x can be taken from the result (for example, 3 x's from 5)
I am working in c#
Thanks in advance, any help is greatly appreciated! Fin
Answer by kalen_08 · Jul 20, 2018 at 09:00 PM
here is what works for me...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class ObjectSpacing : MonoBehaviour
{
[SerializeField] Vector3 spacing = new Vector3 (1,0,0);
// for this to work all gameObjects to be sorted must be child objects.
// they will start from the origin of this object
//if you want this changed let me know
void Update ()
{
var pos = transform.position;
foreach (Transform child in transform)
{
if (child.gameObject.activeSelf == true)
{
child.position = pos;
pos += spacing;
}
}
}
}