NullReferenceException on enemy.RewardGold();

Hi, I’m having the exact same problem as the person here, and the answer given does not make sense. There is no relevant field exposed in the inspector.

After some troubleshooting, enemy.RewardGold(); works just fine when used in the enemyMover class. Something in my enemyHealth class is wrong and I can’t identify the issue. Could someone please help?

public class enemyHealth : MonoBehaviour
{
    [SerializeField] int maxHealth = 5;
    [SerializeField] int currentHealth;
    Enemy enemy;
    void start(){
        enemy = GetComponent<Enemy>();
    }
    void OnEnable(){
        currentHealth = maxHealth;
    }

    void OnParticleCollision(GameObject other){
        ProcessHit();
    }
    private void ProcessHit(){
        currentHealth--;
        if (currentHealth < 1){
            gameObject.SetActive(false);
            enemy.RewardGold(); // <---- This is the line that makes it cry.
        }
    }
}

At a guess, you don’t have an Enemy component on the GameObject when start() happens. If that is the case, then calling enemy.RewardGold() will give you a null reference exception. Alternatively, it may be something in the RewardGold() method causing the issue.

Your enemy is null. The reason your enemy is null is because you never set enemy to anything.

Look at your code. You have a start() method that will never run unless you call it. Unity will not call it. It has to be with an UPPERCASE ‘S’ - Start() - if you want Unity to call it. C# is case-sensitive, so start() and Start() is not the same thing

1 Like

Oh my God, I knew it was something dumb. Thank you. I’ve gotta go to work but I’m gonna be capitalizing that Start() method once I’m home.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms