- Home /
My shooting system wont work, help
I am making a 2D platformer shooter game. After coding for an hour or so I tried it out but to my disappointment, it gave an error. I have now been trying to fix it for an hour but has stumped me.
I get these two errors
NullReferenceException: Object reference not set to an instance of an object
ShootingScript.Shoot (BulletInfo bullet) (at Assets/Scripts/ShootingScript.cs:111)
ShootingScript.Update () (at Assets/Scripts/ShootingScript.cs:40)
NullReferenceException: Object reference not set to an instance of an object
ShootingScript.Start () (at Assets/Scripts/ShootingScript.cs:25)
This is my script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShootingScript : MonoBehaviour
{
[SerializeField]
public WeaponList[] weaponLists;
WeaponScriptableObj currentWeapon;
BulletInfo bullet1;
BulletInfo bullet2;
int currentAmmo;
int maxAmmo;
int oldCurrentAmmo;
int oldWeaponSlot;
public GameObject blankBullet;
public GameObject firePoint;
void Start()
{
bullet1 = currentWeapon.regularBullets; <-----Line 25
bullet2 = currentWeapon.specialBullets;
ChangeWeapon(1);
}
void Update()
{
//Firing input
if (Input.GetButton("Fire1") && currentAmmo >= 1)
{
Shoot(bullet1);
}
if (Input.GetButtonDown("Fire2") && currentAmmo >= 2)
{
Shoot(bullet2); < -------- Line 40
}
public void Shoot(BulletInfo bullet)
{
//Shooting logic
GameObject currentShotBullet = Instantiate(blankBullet, firePoint.transform.position, firePoint.transform.rotation);
currentShotBullet.GetComponent<BlankBullet>().FireBullet(bullet.bulletSpeed, bullet.damage, bullet.range, bullet.bulletSprite); <------ Line 111
}
}
Answer by n_rusev · Apr 04, 2020 at 06:32 AM
You never initialize your WeaponScriptableObj currentWeapon; , so when you first reference it in Line 25 you get an error, since this object is null, which means your bullet1 and bullet2 are null as well - error at line 40. At line 111 your BulletInfo bullet parameter is probably null again. To fix this either make WeaponScriptableObj currentWeapon public and set it to something in the editor, or initialize it in your start method before trying to initialize bullet1 and bullet2.
Switching the order of my start method made it work perfectly, Thank you
Your answer
Follow this Question
Related Questions
My Unity 2D platoformer shooter question. 0 Answers
move, destroy self, instantiate again, repeat. 2 Answers
Why isn't my instance of an object moving? 1 Answer
I cant get my 2d shooting script to work? 2 Answers
How to destroy only one GameObject??? 0 Answers