Failing to reference an instantiated object

I am trying to instantiate an enemy object with some input parameters for the enemy’s health and damage like this:

if (Input.GetKeyDown(KeyCode.T))
        {
            GameObject enemy = Instantiate(whatToSpawn, this.transform.position, this.transform.rotation) as GameObject;
            enemy.GetComponent<Enemy>().changeStats(health, damage);
        }

it does spawn the enemy object, but it fails to create a reference to it, and I get "NullReferenceException: Object reference not set to an instance of an object" error in Unity. What am I doing wrong? I have looked at several threads where this is how people pass parameters to instantiated objects.

I have made sure that the newly instantiated object prefab does in fact have an Enemy component and that it contains the changeStats() method.

did you initialize your public variable in Inspector? probably when you create an object in script and it is public, you will see the variable in inspector and you need to give it a parameter to initialize.

Hope this can solve the problem

Try:

GameObject enemy = (GameObject)Instantiate(whatToSpawn, this.transform.position, this.transform.rotation);

make sure whatToSpawn is a GameObject, or your code will choke when attempting to cast with as and null will be returned