hi.
in somme loop in start function , i spawn gameobject (g.o.) , randomly in a volume.
before instanciating each g.o. , i check if it random position won’t place it inside somme early created g.o. (in previous iteration of loop)
the fact is overlapSPhere don’t detect any collision (empty Collider array returned) and it should.
i try do do this from update() instead of start() : no better result.
i do not want ot to create each g.o. succesivley , i.e. frame by frame , because i have a large number of g.o. to create.
thanks a lot for your advise
nb you probably won’t believe me if i said that the same function correctly work in first version (lighter) of my sofware :(((
first of all, you say you need to spawn a large number of game objects. when you call overlapsphere you are asking unity to check the distance formula on three axis against the other gameobjects in the scene. the distance formula is heavy on a cpu because it invoves square roots. not a big deal for a couple dozen objects or maybe even a hundred. but as you spawn more objects into your scene the number of calculations to call overlap sphere get exponentially higher and can start creating lag in your game!
here is another way. this code does not slow down when checking acceptable spawn locations into the thousands.
to garantee distance between spawns
it uses an adjustable 1000 by 1000 grid of bools to check off circular locations which is virtually nothing to modern RAM memory. thought i would share.
using UnityEngine;
using System.Collections.Generic;
public class del : MonoBehaviour {
public int dist = 8;
bool [,] used;
public int lvl = 1000;
public float fidelity = .5f;
List<Vector2> circle;
void Start (){
circle = new List<Vector2> ();
int x = dist;
while (x>-dist) {x--;
int y = dist;
while (y>-dist) {y--;
if(Vector3.Distance(Vector3.zero,new Vector3(x,y,0))<dist){
circle.Add(new Vector2(x,y));
}
}}
used = new bool[lvl,lvl];
//spawn 5000 items not more than dist*fidelity from each other
for (int i = 0; i < 5000; i++) {
spawn ();
}}
void spawn (){
int distance = 5;int timeout = 0;
while (true) {timeout++;
if(timeout == 5000){print("oops...i could not find an open spot");break;}
int x = Random.Range(0,lvl);
int y = Random.Range(0,lvl);
if(!used[x,y]){
GameObject g = GameObject.CreatePrimitive(PrimitiveType.Cube);
g.transform.position = new Vector3(x*fidelity,y*fidelity,0);
for (int i = 0; i < circle.Count; i++) {
int xx = x+(int)circle*.x;*
_ int yy = y+(int)circle*.y;_
_ if(xx>-1&&yy>-1&&xx<lvl&&yy<lvl){_
_ used[xx,yy]=true;}*_
* } break;}*
* }*
* }*
}