Ok so ive created a prefab of an obstacle avoidance bot and am attempting to clone it. Problem is, only one of the instances works correctly, the rest just sit there. The bots are supposed to turn left when right sensor is triggered and vice versa. The instantiation code:
public int populationSize = 10;
public GameObject carPrefab;
public Vector2 spawnPosition;
public static float speed = 2f;
private GameObject[] cars;
// Use this for initialization
void Start () {
cars = new GameObject[populationSize];
for (int i = 0; i < populationSize; i++) {
spawnPosition = new Vector2((1.0f*i)-2,3.83f);
cars [i] = GameObject.Instantiate (carPrefab,spawnPosition,Quaternion.identity);
}
}
// Update is called once per frame
void Update () {
}
The prefab scripts: (Left Sensor and Right Sensor are children of CarMovement)
public float speed = 2f;
public static Rigidbody2D rb2d;
// Use this for initialization
void Start () {
rb2d = GetComponent<Rigidbody2D> ();
}
// Update is called once per frame
void Update () {
rb2d.transform.Translate (Population.speed * Time.deltaTime, 0, 0);
}
Left Sensor:
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerStay2D (Collider2D other){
Debug.Log ("LEFT");
CarMovement.rb2d.rotation -= 5;
}
Right sensor:
Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine;
public class RightSensor : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerStay2D (Collider2D other){
Debug.Log ("RIGHT");
CarMovement.rb2d.rotation += 5;
}
Any help would be greatly appreciated. I have no idea whats going on.