- Home /
Player projectile not linked to instance of object
Hey guys,
New developer here so sorry for what will probably be an obvious question. I'm developing a 2d platformer and am trying to get my player character to fire in the direction the mouse is pointed. I think what I've stitched together is mostly correct however I keep getting the error: "NullReferenceException: Object reference not set to an instance of an object Player.Update () (at Assets/Scripts/Player.cs:78)"
My code for firing the projectile looks like this:
public GameObject projectile;
public float projectileSpeed = 10.0F;
void Update() {
//Gun firing
if (Input.GetButtonDown ("Fire2")) {
print ("Fired Gun");
nextFire = Time.time + fireRate;
Vector3 aimPosition = Input.mousePosition;
aimPosition.z = transform.position.z - Camera.main.transform.position.z;
aimPosition = Camera.main.ScreenToWorldPoint(aimPosition);
var rotation = Quaternion.FromToRotation(Vector3.up, aimPosition - transform.position);
Rigidbody2D projectileClone = Instantiate(projectile, transform.position, rotation) as Rigidbody2D;
projectileClone.velocity = aimPosition.normalized * projectileSpeed;
}
}
From there I drag the prefab projectile prefab onto the players projectile variable in the inspector so that it is definitely highlighting the projectile prefab when I hover over the variable in the inspector. It seems like I'm linking the projectile prefab correctly but the Null reference error would indicate otherwise. Line 78 is the very last in that code snippet for reference. I'd be much appreciative if anyone clue me into what I'm doing wrong here.