Hello guys, I am working on simple tower defense game and I have a problem with adding GameObjects I instantiated to list. Simply, when I add instance to a list, another instance will not be instantiated…
This code is for spawning enemies and adding them to list.
using UnityEngine;
using System.Collections;
public class GameController : MonoBehaviour {
public Transform spawnPoint;
public GameObject enemy;
public GameObject tower;
private Ray ray;
private RaycastHit hit;
// Use this for initialization
void Start () {
StartCoroutine(SpawnMinions());
}
// Update is called once per frame
void Update () {
if(Input.GetButtonDown("Fire1")) {
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray.origin, ray.direction * 100f, out hit)) {
Instantiate(tower, hit.point + Vector3.up * 0.5f, Quaternion.identity);
}
}
}
IEnumerator SpawnMinions() {
while(true) {
for(int i = 0; i < 5; i++) {
GameObject enemyInstance = Instantiate(enemy, spawnPoint.position, transform.rotation) as GameObject;
yield return new WaitForSeconds(0.5f);
Tower.enemies.Add(enemyInstance); // when I remove this line of code, it instantiates 5 enemies. But with it, it instantiates only 1... It behaves like return command in function.
}
yield return new WaitForSeconds(3f);
}
}
}
And then here is Tower script… Code should check, if there is at least 1 enemy in list and if it is and is in specific range from tower, then start shoot enemy until it is destroyed:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Tower : MonoBehaviour {
public GameObject bullet;
public static List<GameObject> enemies;
public int time;
void Start() {
}
void Update() {
time = (int)(Time.time);
if(enemies.Count > 0) {
for(int i = 0; i < enemies.Count; i++) {
while(enemies*.gameObject != null) { // while current object exists*
if(time % 2 == 0 && (Vector3.Distance(transform.position, enemies*.transform.position) < 2)) {*
Instantiate(bullet, transform.position, transform.rotation);
bullet.SendMessage(“Fire”, enemies*.transform.position - transform.position);*
}
if(Vector3.Distance(transform.position, enemies*.transform.position) > 2) break;*
}
}
}
}
}
And really simple bullet script:
using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour {
* // Use this for initialization*
* void Start () {*
* }*
* // Update is called once per frame*
* public void Fire (Transform target) {*
_ rigidbody.AddForce(target.position * 1.5f * Time.deltaTime);
* }
}
Unity writes this error, when I start the game… Really don’t know what does it mean:
NullReferenceException: Object reference not set to an instance of an object
GameController+c__Iterator0.MoveNext () (at Assets/Scripts/GameController.cs:39)
And when I instantiate tower, it keeps writing:
NullReferenceException: Object reference not set to an instance of an object
Tower.Update () (at Assets/Scripts/Tower.cs:19)
(Saying, that error is on this line of code: if(enemies.Count > 0))*_