How to spawn Prefab anywhere within Box Collider 2D?
I have a lot of experience in Unreal and know it's really simple there, I am new to Unity and not sure how I would write code to spawn a prefab anywhere within the dimensions of a Box Collider 2D.
Answer by Vega4Life · Aug 14, 2019 at 03:12 PM
Here is a quick script. I am just grabbing the size of the collider, getting a random range from those sizes / 2 (because its based on center). Then adding this range to the position of the collider. There is a note to reduce the random range by half the size of the prefab if you wanted it to be perfectly in the box. That's up to you though.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnInCube : MonoBehaviour
{
[SerializeField] GameObject prefab;
[SerializeField] BoxCollider2D bc;
Vector2 cubeSize;
Vector2 cubeCenter;
private void Awake()
{
Transform cubeTrans = bc.GetComponent<Transform>();
cubeCenter = cubeTrans.position;
// Multiply by scale because it does affect the size of the collider
cubeSize.x = cubeTrans.localScale.x * bc.size.x;
cubeSize.y = cubeTrans.localScale.y * bc.size.y;
}
private void Start()
{
GameObject go = Instantiate(prefab, GetRandomPosition(), Quaternion.identity);
}
private Vector2 GetRandomPosition()
{
// You can also take off half the bounds of the thing you want in the box, so it doesn't extend outside.
// Right now, the center of the prefab could be right on the extents of the box
Vector2 randomPosition = new Vector2(Random.Range(-cubeSize.x / 2, cubeSize.x / 2), Random.Range(-cubeSize.y / 2, cubeSize.y / 2));
return cubeCenter + randomPosition;
}
}
private Vector2 GetRandomPosition()
{
Vector2 RandomPositionTop = new Vector2(Random.Range(-NorthBoxSize.x / 2, -NorthBoxSize.x / 2), Random.Range(-NorthBoxSize.y / 2, NorthBoxSize.y / 2));
Vector2 RandomPositionBottom = new Vector2(Random.Range(-SouthBoxSize.x / 2, SouthBoxSize.x / 2), Random.Range(-SouthBoxSize.y / 2, SouthBoxSize.y / 2));
Vector2 RandomPositionRight = new Vector2(Random.Range(-EastBoxSize.x / 2, EastBoxSize.x / 2), Random.Range(-EastBoxSize.y / 2, EastBoxSize.y / 2));
Vector2 RandomPositionLeft = new Vector2(Random.Range(-WestBoxSize.x / 2, WestBoxSize.x / 2) Random.Range(-WestBoxSize.y / 2, WestBoxSize.y / 2));
int Randomizer = Random.Range(0, 4);
if (Randomizer == 0)
{
return NorthBoxCenter + RandomPositionTop;
}
else if (Randomizer == 1)
{
return SouthBoxCenter + RandomPositionBottom;
}
else if (Randomizer == 2)
{
return EastBoxCenter + RandomPositionRight;
}
else if (Randomizer == 3)
{
return WestBoxCenter + RandomPositionLeft;
}
}
Your answer
Follow this Question
Related Questions
Client Spawning Player Objects 0 Answers
Spawning issues 1 Answer
my objects is spawning on the wall 1 Answer
Random spawn script 1 Answer
make enemy fire at randomly times? 0 Answers