Search Unity

Instantiating new Game Objects

Discussion in 'Scripting' started by adri1992, Feb 11, 2016.

  1. adri1992

    adri1992

    Joined:
    Dec 14, 2015
    Posts:
    34
    Hi!

    I've a problem... =(

    I have a Game Object inside a scene, and new Game Objects are instantiated through a script around a radius of the first Game Object mentioned.

    Well, when multiple Game Objects ara instantiated with random position around this radius, sometimes they are above other Game Objects previously instantiated =(

    Any idea to solve this problem?

    Thanks so much!
     
  2. _met44

    _met44

    Joined:
    Jun 1, 2013
    Posts:
    633
    Hello, there are numerous ways to solve this depending on your context.

    One way is to raycast downwards the position you rolled and roll/raycast again until you hit terrain, and if you're not in a big hurry for the spawn to happen you can spread it over several frames for a smaller CPU cost. (works well in not too crowded situations and with not too wide objects, it's memory efficient and requires little setup, i believe it is the simplest solution)

    If you can afford the CPU you can use spherecast instead to better match the shape of your object.

    Alternatively you can create a grid-like system that allows you to know if there's an object at a give position or not for a CPU cost of 0 but with a memory fingerprint depending on the size of the grid. Note that if your objects move and you wish newly spawned ones to spawn in different place from objects that just visited the slot you can do it with such system (ie: an object visiting a square gives its value +1, and when the slot becomes empty you remove 0.2 per second or whatever fits your need until it reaches 0 and can accept a spawn again)
     
    adri1992 likes this.