Reputation: 345
I am getting "NullReferenceException: Object reference not set to an instance of an object", I dont know what is wrong in my code:
I have a class "EnemyInfo" as
public class EnemyInfo {
public GameObject enemyObject;
}
In another class "Enemies" I am using it like this:
public class Enemies : MonoBehaviour {
public static List<GameObject> gos;
public static List<EnemyInfo> gosN = new List<EnemyInfo>();
void FixedUpdate() {
gos = new List<GameObject>(GameObject.FindGameObjectsWithTag("enemy"));
gosN.Add(null)
gosN[0].enemyObject = gos[0].gameObject //here I am getting error, dont know y :S
}
}
Upvotes: 0
Views: 1682
Reputation: 2937
The list is empty, you don't have an instance to refer to public instance members
Upvotes: 1
Reputation: 35594
Clearly, after
gos.Add(null)
you have gos[0] == null
. So gos[0].gameObject
dereferences null
-reference.
Upvotes: 0
Reputation: 499132
I suspect gos[0].gameObject
is the issue.
If gos
is empty to begin with, doing gos.Add(null)
, adds a null
entry.
You then access this value with gos[0]
and try to invoke a member on it - since this is a null
, you are getting a NullReferenceException
.
Don't add a null
GameObject
.
Upvotes: 2
Reputation: 25595
Thats because gos
contains only one object which is null.
that's why you're getting a NullReferenceException
.
Upvotes: 5