Here’s another probably stupidly simple question, but I’m starting out and really apreciate any help
I’m trying to figure out c# in unity by trying a 2d boids simulation. I’ve got to the FIRST step of spawning 5 boids randomly on the screen (done so by taking the camera specs and randomizing values within those bounds) and instantiating within a for loop. Problem is, Unity crashes every time I click play to check it out.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoidSpawnScript : MonoBehaviour
{
public GameObject Boid;
public int NumberOfBoids;
void SpawnBoids() {
float cHeight = Camera.main.orthographicSize * 2f;
float cWidth = cHeight * 2f * Camera.main.aspect;
for (int i = 0; i<NumberOfBoids; i++ ){
float randomY = Random.Range(-cHeight/2f, cHeight/2f);
float randomX = Random.Range(-cWidth/2f, cWidth/2f);
Vector2 spawnPosition = new Vector2(randomX, randomY);
GameObject newBoid = Instantiate(Boid, spawnPosition, Random.rotation);
}
}
// Start is called before the first frame update
void Start()
{
SpawnBoids();
}
// Update is called once per frame
void Update()
{
}
}
I’ve written probably 5 lines here (exaggeration) I have no idea where it’s going wrong. I’ve already gone through and tried literally anything I can think of, which isn’t much, because I’ve never done this before.
EDIT: So in my desperation I recreated the unity project and copy and pasted the code you see above, except this time changed number of boids to 2…

this leads me to think my for loop is broken but I know enough to know that it’s syntaxed correctly
>Solution :
Your attached SS tells it all. (clone)… (clone)(clone)… is because you have added the same script on instantiated boids too. Each one of them instantiates more boids and it’s an endless loop to me.