I’m new to Unity and C# (and OOP in general) and I’m having difficulty working with lists.
In the following code I’m successfully instantiating new objects and adding them to the list. Then when I try to output the position to Debug.Log I get an error: “Object reference not set to an instance of an object”. It compiles and runs fine until it gets to the Debug.Log line. How can I grab a specific instance of an object from a list by that object’s index from within the list?
Thank you!
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GameController : MonoBehaviour {
public GameObject unitToSpawn;
private List<Tank> TankList = new List<Tank>();
public Tank tank;
public int numTanks;
void Start () {
for (int i = 0; i < numTanks; i++) {
Vector3 spawnPosition = new Vector3 (Random.Range (-5, 5), 1, Random.Range (-5, 5));
Quaternion spawnRotation = Quaternion.identity;
TankList.Add (Instantiate (unitToSpawn, spawnPosition, spawnRotation) as Tank);
}
for (int i = 0; i < numTanks; i++){
Debug.Log ("i = " + i + " : " + TankList*.transform.position);*
this is not a problem with Getting the position in the list, you are doing that part correctly. Your not setting a value to Tank in the Start function, So when you make these new objects as type Tank, your giving them unknown values. instead of doing it “as Tank” do it “as GameObject” or “as Transform” and it should work
So I ended up doing something similar to the way a list of Enemy objects is made in the [2D Roguelike Tutorial][1]. In case anyone else comes across this problem here is the solution I got to:
GameController.cs:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GameController : MonoBehaviour {
public static GameController instance = null;
public GameObject tankPreFab;
public int numTanks;
private List<Tank> tankList;
void Awake (){
instance = this;
tankList = new List<Tank>();
}
void Start () {
for (int i = 0; i < numTanks; i++) {
Vector3 spawnPosition = new Vector3 (Random.Range (-5, 5), 1, Random.Range (-5, 5));
Quaternion spawnRotation = Quaternion.identity;
Instantiate(tankPreFab, spawnPosition, spawnRotation);
}
for (int i = 0; i < numTanks; i++){
tankList*.ID = i;*
_ Debug.Log ("i = " + i + " : " + tankList*.transform.position);_
_ }_
_ }_
_ public void AddTankToList(Tank script)_
_ {_
_ tankList.Add(script);_
_ }_
_}*_
And here is Tank.cs (which is attached to the Tank Prefab)
using UnityEngine;
* using System.Collections;*
* public class Tank : MonoBehaviour {*
* public int ID; //unique ID for each tank*
* void Awake(){*
* GameController.instance.AddTankToList (this);*
* }*
* }*
And now I have a list of tanks!
_*[1]: Learn game development w/ Unity | Courses & tutorials in game design, VR, AR, & Real-time 3D | Unity Learn