Null reference on instantiated object

I have this code

var meleeDamage: int = 10;
var rangeDamage: int = 10;
var magicDamage: int = 10;
var meleeDist: float = 5;
var attackStyle: String = "magic";
var bullet: GameObject;

function Update(){
	if (Input.GetButtonDown("Fire1")){
		Attack();
	}
}

function Attack(){
	if (attackStyle == "magic"){
		var inst = Instantiate(bullet, transform.position, transform.rotation);
		Physics.IgnoreCollision(inst.collider, transform.root.collider); // ignores collisions between the bullet and the character controller
		inst.rigidbody.AddRelativeForce(0,0,1500);
		var magic: playerDamage = inst.gameObject.GetComponent(playerDamage);
		magic.damage = magicDamage;
		magic.attackStyle = attackStyle;
	}
}

In Unity it give me null reference error point to “magic.damage = magicDamage;”

What did I do wrong here?

1 Answer

1

Can you verify that the bullet prefab you are instantiating has the “playerDamage” script on it?

Edit: Also verify that you have linked the prefab into the public inspector property for bullet.

If it does could you try the following code?

    var meleeDamage: int = 10;
    var rangeDamage: int = 10;
    var magicDamage: int = 10;
    var meleeDist: float = 5;
    var attackStyle: String = "magic";
    var bullet: GameObject;
     
    function Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            Attack();
        }
    }
     
    function Attack()
    {
        if (attackStyle == "magic")
        {
            var inst = Instantiate(bullet, transform.position, transform.rotation) as GameObject;
            Physics.IgnoreCollision(inst.collider, transform.root.collider); // ignores collisions between the bullet and the character controller
            inst.rigidbody.AddRelativeForce(0,0,1500);
            var magic: playerDamage = inst.GetComponent(playerDamage);
            magic.damage = magicDamage;
            magic.attackStyle = attackStyle;
        }
    }

I have updated it to cast the bullet that was instantiated into a GameObject and removed the need for retrieving the GameObject from inst.gameObjectGetComponent(playerDamage) line.

Of course, it has to be something simple I forget. I didn't put the script on it in Unity. Thank you.

:P It happens. You're welcome.