Hi,
I’m having a trouble with a trigger that won’t get a GameObject and always give me a NullReferenceException.
I have one character with a big Sphere Collider as an empty child. “Is trigger” is checked and the trigger function works but when I try to get the other GameObject, it will always return null.
This is the code I use:
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Enemy")
{
currentEnemy = other.GetComponent<EnemyController>().listIndex(0, false);
enemiesInRange.Add(Spawner.enemyPool[currentEnemy]);
}
}
What I’m trying to do with “currentEnemy” is get the index of the object in the pool (the pool was previously made in the Spawner script) so I can add that object to a private list of enemies that are in range. I’m sending (0, false) just because I use the same function to also write objects in the pool from the spawner, so it’s just telling it that I’m not adding anything, I only want the return.
I also tried:
if (other.tag == "Enemy")
{
EnemyController enemy = other.GetComponent<EnemyController>();
currentEnemy = enemy.listIndex(0, false);
enemiesInRange.Add(Spawner.enemyPool[currentEnemy]);
}
But also no luck. I’m using this code in another script and it works fine:
if (other.tag == "Enemy")
{
EnemyController enemyController = other.GetComponent<EnemyController>();
if (enemyController != null)
enemyController.takeDamage(damage);
}
What am I doing wrong?
Thank you!
EDIT: The line that gives me the NullReference is
currentEnemy = other.GetComponent().listIndex(0, false);
or, in the second script:
EnemyController enemy = other.GetComponent();