When i instantiate prefabs randomly ,they are getting into other prefabs.

Hi

İ am having an issue when i instantiate prefabs to the scene randomly .For example prefabs(or part of they) getting into other prefabs.All the prefabs have colliders,most of them have more than one,but they haven’t rigidbody.İf i add rigidbody to them ,the problem is solving.But it is not quite good solution because this time they are being contiguous to each other.i think i should declare illegal instantiated prefabs’ zones in some way.but i can’t.is there any person who has solution for this?

Thanks in advance.

P.s.:The project is 3d and i use c#…

Hi.
You can try to check if there is alrealy an object where to try to spawn a new one.

Ex you whant to place a object in the map
Before instantiate your prefab Make a OverlapBox of the size of the object you are tryng to spawn (Unity - Scripting API: Physics.OverlapBox) ← use this to make a overlapBox
(Unity - Scripting API: Renderer.bounds) ← use this to know the size of the overlapBox
Then if the overlapbox didnt hit a thing you can spawn your prefabs.

1 Like

I have the same scenario and use rays to check for any objects before instantiating.

1 Like

Use OnTriggerEnter like this

class DetectOverlap : MonoBehaviour
{
        private float spawnTime = 0f;
    void Start()
    {
        spawnTime = Time;
    }
    void OnCollisionEnter(Collision col)
    {
        DetectOverlap overlap = col.collider.GetComponent<DetectOverlap>();
        if(overlap != null)
        {
            if(overlap.spawnTime > spawnTime)
            {
                Vector3 pos = col.collider.transform.position;
                //Randomize pos;
                col.collider.transform.position = pos;
            }
        }
    }
}

if you are instancing them all at the same time you shouldn’t rely on the spawnTime, use something else to decide which of the two object to re position.

1 Like

Thank you all for the your responses.
i handled it using OverlapBox as Akzafield suggested.
Firstly i detected if there are any prefabs in the place where i am trying to instatiate other prefabs .And then , i repositioned them if there are…

hi again.this time i’m having another problem that related to OverlapBox.Let’s say the given object is a cube and it has 2 colliders which are not intersact with each other.I am creating OverlapBoxes that have these colliders’ center and extent values.When the colliders(and OverlapBox) have zero rotation ,it works,it collects 2 colliders. But when colliders(and OverlapBox) have a value that different from zero for rotation, OverlapBox collects 4 colliders.So,first OverlapBox is collecting first and second colliders and second OverlapBox is collecting same colliders too.How come it is breaking when rotation value different from zero?