Trigger not getting GameObject

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();

It finally works!

Thanks to @Harinezumi I found the error.

I had one parent with a rigidbody and two colliders on child objects (with no rigidbody) and when I was trying to get the script from them, they didn’t give me anything back because the script was on the parent.

There are a bunch of ways to solve this, like having scripts on colliders and basically relaying them to the parent but what I use is GetComponentInParent as in my case, it works great because I only have one component of that type (EnemyController) in any of the parents. I don’t know if this is the best or most optimized way to use it for something like bullets hitting enemies (there are a lot of bullets) but it works.

This is the result:

private void OnTriggerEnter(Collider other)
{
        if (other.tag == "Enemy")
        {
            currentEnemy = other.gameObject.GetComponentInParent<EnemyController>().listIndex(0, false);

            enemiesInRange.Add(Spawner.enemyPool[currentEnemy]);
        }
}

change if statement

if(other.collider.tag == "Enemy")
{
 // your code
}