0
\$\begingroup\$

I'm trying to instantiate my CarMovement class with my population class for a Genetic Algorithm, but when i run the project, the car prefab doesnt spawn.

Everything is wired up in the inspector correctly. Anyone know whats going on?

Here's the population class:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Population : MonoBehaviour {

    public int populationSize = 10; 
    private CarMovement[] cars;

    // Use this for initialization
    void Start () {
        cars =  new CarMovement[populationSize];
        for (int i = 0; i < populationSize; i++) {
            cars [i] = new CarMovement ();
            cars [i].score = 1+i;
            Debug.Log (cars [i].score);
        }
        //cars[0].Start();
    }

    // Update is called once per frame
    void Update () {
    }
}

Here's the CarMovement/Individual class:

public class CarMovement : MonoBehaviour {

    public float speed = 2f;
    public Rigidbody2D rb2d;
    public Vector2 spawnPosition = new Vector2((1.0f)*0.1f,3.83f);
    public int score;
    public GameObject carPrefab;

    // Use this for initialization
    public void Start () {
        rb2d = GetComponent<Rigidbody2D> ();
        GameObject.Instantiate (carPrefab,spawnPosition,Quaternion.identity);
        Debug.Log ("YAAAA");

    }

    // Update is called once per frame
    public void Update() {
        rb2d.transform.Translate (speed * Time.deltaTime, 0, 0);

    }    
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ It's unusual to use new to construct a class deriving from MonoBehaviour. Is there a reason your Population class doesn't Instantiate() the CarMovement instances it needs from a prefab itself? \$\endgroup\$
    – DMGregory
    Aug 31, 2017 at 3:26

1 Answer 1

1
\$\begingroup\$

It looks like you want something like this:

public class Population : MonoBehaviour {

    // Assign this Inspector variable to point at your prefab.
    public CarMovement carPrefab;

    public int populationSize = 10; 

    // The Population class does the spawning now, so it can hold the spawn position.
    public Vector2 spawnPosition = new Vector2(0.1f, 3.83f);

    private CarMovement[] cars;

    void Start () {
        cars =  new CarMovement[populationSize];
        for (int i = 0; i < populationSize; i++) {
            cars [i] = (CarMovement)Instantiate(
                           carPrefab,
                           spawnPosition,
                           Quaternion.identity);
            cars [i].score = 1+i;
        }    
    }    
}

This Instantiates your cars and grabs a handle to the CarMovement script instance already on them (assuming your prefab has a CarMovement on it), rather than trying to create an instance of the component free-floating without a GameObject attached.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .