Hello,
I have an enemy controller script that has a list holding a couple of different collectible items:
public List<Transform> collectibles = new List<Transform>();
I add these collectibles in the Inspector.
I have another script attached to my player which uses OnTriggerEnter2D to detect the collision with an enemy and drops one of the items. I am struggling to get it to access the list from the enemy controller script to instantiate a random collectible:
public GameObject deathEffect;
public float chanceToDrop;
private void OnTriggerEnter2D(Collider2D other) {
if (other.CompareTag("Enemy")) {
//other.transform.parent.gameObject.SetActive(false);
Instantiate(deathEffect, other.transform.position, other.transform.rotation);
PlayerController.instance.Bounce();
EnemyController enemyController = other.gameObject.GetComponent<EnemyController>();
Debug.Log(enemyController);
float dropSelect = Random.Range(0, 100);
if (dropSelect <= chanceToDrop) {
Instantiate(enemyController.collectibles[Random.Range(0, enemyController.collectibles.Count-1)], other.transform.position, other.transform.rotation);
}
}
}
When I run the game, I get the following error in the console:
NullReferenceException: Object reference not set to an instance of an object
StompBox.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/StompBox.cs:21)
Line 21 refers to the line where I instantiate the random collectible. My Debug returns NULL, so I am obviously doing something wrong when trying to access the List, but I don’t know what?
Many Thanks,
J