- Home /
How to change the overlapping Game Object position ?
I am trying to spawn the list of game objects at random positions. Now this can also lead to overlapping among the objects and spawning and destroying game objects again and again can be pretty taxing, so my way out is to move the overlapped game objects away from other it overlapped with by certain amount.
Now in my program, i want to spawn a list of non overlapping random positioned game objects with above mentioned approach for about 3 seconds and within this time frame i will use my code then after this all objects gets destroyed and and again spawn another list of game objects and do the same. My code to move overlapped objects gives an error of "NullReferenceException: Object reference not set to an instance of an object"
The code for this is as down here,
private void RepositionTheNodes(ref List<GameObject> blankList, float gap, bool run = true)
{
while (true)
{
if (blankList.Count == 0) return;
if (!run) return;
run = false;
foreach (GameObject node in blankList)
{
Collider2D[] results = new Collider2D[blankList.Count];
var size = Physics2D.OverlapCircleNonAlloc(node.transform.position, GetThePrefabDimension.Height * 0.5f, results);
if (size <= 0) continue;
run = true;
foreach (Collider2D other in results)
{
var position = node.transform.position;
Vector3 directionVector = position - other.transform.position;
float offset = Mathf.Abs(GetThePrefabDimension.Height - Vector3.Magnitude(directionVector) + gap);
directionVector = directionVector.normalized * offset;
position += directionVector;
if (WithinBounds(position)) node.transform.position = position;
}
}
}
}
Your answer

Follow this Question
Related Questions
How to Detect a gameObject when Clicked near it? 2 Answers
Only sideways colliding detection 2 Answers
Second Coroutine isn't working Unity 1 Answer