i’m trying to instantiate prefab on squared object, but i want to prevent it to be instantiated near or on the edges of the object.
Well, first you should calculate the edges of your object. If it’s just a cube, and you know how wide the thing is, you can calculate it pretty simply. Sphere is also easy ( just the radius ). Then when you are going to instantiate, check if the target position is inside the edges. Not that hard? Just break everything into pieces.
public Vector3 squarePos; //world position of your square
public Vector3 squareSize; //x = width, y = height, z = length of box
public float squareBorder; //how far away from the edges you want the spawn to stay
Vector3 realSquareSize;
void Awake(){
realSquareSize = squareSize - (Vector3.one * squareBorder));
void SpawnPrefabOnSquare(GameObject thePrefabYouWantToSpawn){
var spawnPos = squarePos + new Vector3(Random.Range(-realSquareSize.x, realSquareSize.x), Random.Range(-realSquareSize.y, realSquareSize.y), Random.Range(-realSquareSize.z, realSquareSize.z)) * 0.5f;
Instantiate(thePrefabYouWantToSpawn, spawnPos, Quaternion.identity);
}
1 Like