Hello GameDev Community,
I have a problem with this pice of code. If I start the "Game", it crashes right away. Probably is its the list of GameObjects or the foreach loop. I have no idea how I can solve the problem. Please don't be too strict with me [...]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class TreeGeneratorScript : MonoBehaviour
{
// ####################################################################################################
// GameObject: Tree
public GameObject prefabTree;
public Vector3 minGroundPos; // Vector3( 0, 1, 0)
public Vector3 maxGroundPos; // Vector3(100, 1, 50)
// List of GameObjects with our Trees
public List<GameObject> treeList = new List<GameObject>();
// Number of attempts ( 100 )
public int numRunTry;
// Variables
GameObject newTree;
float distance;
// ####################################################################################################
void Start()
{
// Instantiate a tree in the middle of the Scene
newTree = Instantiate(prefabTree, new Vector3(50, 1, 25), Quaternion.identity);
// Add GameObject to our List
treeList.Add(newTree);
// Call Method: SpawningTrees
SpawningTrees();
}
// ####################################################################################################
void SpawningTrees()
{
// Try 100 times to spawn a tree
for (int i = 0; 1 < numRunTry; i++)
{
// Get a Random Position
Vector3 randomSpawnPos = new Vector3(
Random.Range(minGroundPos.x, maxGroundPos.x),
1,
Random.Range(minGroundPos.z, maxGroundPos.z)
);
foreach(GameObject tree in treeList)
{
// Calculate the distance between our Random Position and each tree from our list
distance = Mathf.Sqrt( Mathf.Pow( (tree.transform.position.x - randomSpawnPos.x), 2) + Mathf.Pow( (tree.transform.position.z - randomSpawnPos.z), 2));
// Check if the distance is smaller 12 between a tree and the Random Position
if(distance < 12)
{
// Random Position is too close to our tree -> new Random Position
break;
}
else if(distance >= 12 && tree == treeList.Last())
{
// Every tree from our list has a min distance of 12 to our Random Position
// Instantiate the final tree
newTree = Instantiate(prefabTree, randomSpawnPos, Quaternion.identity);
// Add tree to our list of trees
treeList.Add(newTree);
break;
}
}
}
}
After I run the code, it should look like this: