Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unity keeps crashing when I click play, even though ive only written about 5 lines

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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…
big bad mistake

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading