This is my first question on Stack Overflow. I am quite the coding newbie, so please bear with me and my horrific code.
void ChickenInstantiate()
{
LocOfChkn.Add(spawnLoc);
int i = 0;
for (int ChickenCount = 0; ChickenCount < maxChickenCount; ChickenCount++)
{
while (Vector3.Distance(spawnLoc, LocOfChkn[i]) < 2)
{
spawnLoc = new Vector3(Random.Range(randXMin, randXMax), Random.Range(randYMin, randYMax), 1);
spawnLoc.z = 5;
i += 1;
if (i >= LocOfChkn.Count)
{
break;
}
}
Instantiate(ChickenPrefab1, spawnLoc, Quaternion.identity);
LocOfChkn.Add(spawnLoc);
i = 0;
}
}
This is some code for instating a prefab but making sure it doesn't instantiate within an area, and frankly I'm not sure how I should fix it- its completely broken; chickens don't appear, I'm not even sure if they spawn in the correct areas, etc. (the first instance of spawnLoc is defined at startup, btw)
I'm using the current latest version of unity and visual studio.
You should Instantiate
a chicken for the first location you add to locOfChkn
. This will serve as both making sure your code is running, and avoid a chickenless spot.
Use VSCode or your favorite IDE to do a step-by-step evaluation of your function, to know exactly what is happening. Barring that, add Debug.Log
s for each step.
Check the hierarchy for any spawned chickens. Maybe they are disabled.
Now for other issues:
Please follow a C# convention for writing code. Chkn and Loc are about as unintuitive as it gets.
If you ignore the z position when evaluating distances, please consider using Vector2.Distance.
Using a field for a value that you only use inside one function is useless. Simply set spawnLoc
as a var inside ChickenInstantiate
.
Here's a cleaned up version of your code
void InstantiateChicken()
{
List<Vector3> chickenPositions = new List<Vector3>();
for (int i = 0; i < maxChickenCount; i++)
{
bool doesCollide;
Vector3 spawnLocation;
do
{
spawnLocation = new Vector3(
Random.Range(randXMin, randXMax),
Random.Range(randYMin, randYMax),
5);
doesCollide = false;
foreach (var pos in chickPositions)
{
if (Vector2.Distance(pos, spawnLocation) < 2f)
doesCollide = true;
}
}
while (doesCollide);
Instantiate(chickenPrefab1, spawnLocation, Quaternion.identity);
chickenPositions.Add(spawnLocation);
}
}
Alternatively, simply place all your chickens by hand, and make them offset their positions by a random factor when they spawn.