2D Platformer Tutorial – How do I add Fire Rate Upgrade in UpgradeMenu

Updated 6 days ago in [A] Brackeys Courses
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
13 on December 3, 2017

This is for a big project for school so please help. I wanted to add a way to upgrade my fire rate in the UpgradeMenu used in the How to Make a 2D Platformer tutorial. Inside of the “PlayerStats” script I add a float called “weaponFireRate” and then in the Start method I set weaponFireRate = weapon.fireRate. Then in the “UpgradeMenu” script I created a private float named “fireRateMultiplier” like the rest of the UpgradeMenu multipliers, and set it equal to 1.3f. I guess unstead of telling you everything I already did, I’ll just post the script. When I hit play it gives me an error and says “NullReferenceException: Object reference not set to an instance of an objectPlayerStats.Start () (at Assets/Scripts/PlayerStats.cs:36)”. The line it’s referring is the one I mentioned above, weaponFireRate = weapon.fireRate. Also when I hit “U” when playing it shows the Fire Rate on Upgrade GUI, but the fireRate says 0 even though I have it set to 5f in the “Weapon” script. When I click Upgrade it let’s me buy it, but the value doesn’t update and the fire rate stays the same when I shoot. Please Help me I need this game to be done for a school project. I’ll Bold the stuff that applies in my codes.

  • Liked by
Reply
2 on December 3, 2017

PlayerStats Script:

using UnityEngine;

public class PlayerStats : MonoBehaviour
{
     public static PlayerStats instance;

     private int _curHealth;
     public int CurHealth
     {
          get { return _curHealth; }
          set { _curHealth = Mathf.Clamp(value, 0, maxHealth); }
     }

     Weapon weapon;

     public int maxHealth = 100;

     public float healthRegenRate = 2f;

     public float movementSpeed = 10f;

     public float weaponFireRate;

     void Awake()
     {
          if (instance == null)
          {
               instance = this;
          }
     }

     void Start ()
     {
          weaponFireRate = weapon.fireRate;
     }

}

 

on December 3, 2017

UpgradeMenu Script:

using UnityEngine;
using UnityEngine.UI;

public class UpgradeMenu : MonoBehaviour {

     [SerializeField]
     private Text healthText;

     [SerializeField]
     private Text speedText;

     [SerializeField]
     private Text fireRateText;

     [SerializeField]
     private float healthMultiplier = 1.3f;

     [SerializeField]
     private float movementSpeedMultiplier = 1.2f;

     [SerializeField]
     private float fireRateMultiplier = 1.3f;

     [SerializeField]
     private int upgradeCost = 50;

     private PlayerStats stats;

     private Weapon weapon;

     void OnEnable ()
     {
          stats = PlayerStats.instance;
          UpdateValues();
     }

     void UpdateValues ()
     {
          healthText.text = stats.maxHealth.ToString();
          speedText.text = stats.movementSpeed.ToString();
          fireRateText.text = stats.weaponFireRate.ToString();
     }

     public void UpgradeHealth ()
     {
          if (GameMaster.Money < upgradeCost)
          {
               AudioManager.instance.PlaySound(“NoMoney”);
               return;
          }

          stats.maxHealth = (int)(stats.maxHealth * healthMultiplier);

          GameMaster.Money -= upgradeCost;
          AudioManager.instance.PlaySound(“Money”);

          UpdateValues();
     }

     public void UpgradeSpeed()
     {
          if (GameMaster.Money < upgradeCost)
          {
               AudioManager.instance.PlaySound(“NoMoney”);
               return;
          }

 stats.movementSpeed = Mathf.Round (stats.movementSpeed * movementSpeedMultiplier);

          GameMaster.Money -= upgradeCost;
          AudioManager.instance.PlaySound(“Money”);

          UpdateValues();
     }

     public void UpgradeFireRate()
     {
          if (GameMaster.Money < upgradeCost)
          {
               AudioManager.instance.PlaySound(“NoMoney”);
               return;
          }

          stats.weaponFireRate = Mathf.Round(stats.weaponFireRate * fireRateMultiplier);

          GameMaster.Money -= upgradeCost;
          AudioManager.instance.PlaySound(“Money”);

          UpdateValues();
     }

}

 

on December 3, 2017

Weapon Script:

using System.Collections;
using UnityEngine;

public class Weapon : MonoBehaviour {

     public float fireRate = 5;
     public int Damage = 10;
     public LayerMask whatToHit;

     public Transform BulletTrailPrefab;
     public Transform HitPrefab;
     public Transform MuzzleFlashPrefab;
     float timeToSpawnEffect = 0;
     public float effectSpawnRate = 10;

     // Handle camera shaking
     public float camShakeAmt = 0.05f;
     public float camShakeLength = 0.1f;
     CameraShake camShake;

     public string weaponShootSound = “DefaultShot”;

     float timeToFire = 0;
     Transform firePoint;

     // Cashing
     AudioManager audioManager;

     // Use this for initialization
     void Awake ()
     {
          firePoint = transform.Find(“FirePoint”);
          if (firePoint == null)
          {
               Debug.LogError(“No firePoint? WHAT?!”);
          }
     }

     void Start ()
     {
          camShake = GameMaster.gm.GetComponent<CameraShake>();
          if (camShake == null)
               Debug.LogError(“No CameraShake script found on GM object.”);

          audioManager = AudioManager.instance;
          if (audioManager == null)
          {
          Debug.LogError(“FREAK OUT! No audiomanager found in scene.”);
          }
     }

     // Update is called once per frame
     void Update ()
     {
          if (fireRate == 0)
          {
               if (Input.GetButton (“Fire1”))
               {
                    Shoot();
               }
          }
          else
          {
               if (Input.GetButton (“Fire1”) && Time.time > timeToFire)
               {
                    timeToFire = Time.time + 1 / fireRate;
                    Shoot();
               }
          }
     }

     void Shoot ()
     {
          Vector2 mousePosition = new Vector2(Camera.main.ScreenToWorldPoint (Input.

mousePosition).x, Camera.main.ScreenToWorldPoint (Input.mousePosition).y);
          Vector2 firePointPosition = new Vector2(firePoint.position.x, firePoint.position.y);
          RaycastHit2D hit = Physics2D.Raycast(firePointPosition, mousePosition-firePoin

tPosition, 100, whatToHit);

          Debug.DrawLine(firePointPosition, (mousePosition-firePointPosition)*100, Color.

cyan);
          if (hit.collider != null)
          {
               Debug.DrawLine(firePointPosition, hit.point, Color.red);
               Enemy enemy = hit.collider.GetComponent<Enemy>();
              if (enemy != null)
               {
                    enemy.DamageEnemy(Damage);
                    //Debug.Log(“We hit ” + hit.collider.name + ” and did ” + Damage + ” dama

ge.”);
               }
          }

          if (Time.time >= timeToSpawnEffect)
          {
               Vector3 hitPos;
               Vector3 hitNormal;

               if (hit.collider == null)
               {
                    hitPos = (mousePosition – firePointPosition) * 30;
                    hitNormal = new Vector3(9999, 9999, 9999);
               }
               else
               {
                    hitPos = hit.point;
                    hitNormal = hit.normal;
               }

               Effect(hitPos, hitNormal);
               timeToSpawnEffect = Time.time + 1 / effectSpawnRate;
          }
     }

     void Effect (Vector3 hitPos, Vector3 hitNormal)
     {
          Transform trail = Instantiate(BulletTrailPrefab, firePoint.position, firePoint.rotatio

n) as Transform;
          LineRenderer lr = trail.GetComponent<LineRenderer>();

          if (lr != null)
          {
               lr.SetPosition(0, firePoint.position);
               lr.SetPosition(1, hitPos);
          }

          Destroy(trail.gameObject, 0.04f);

          if (hitNormal != new Vector3 (9999, 9999, 9999))
          {
               Transform hitParticle = Instantiate(HitPrefab, hitPos, Quaternion.FromToRotat

ion(Vector3.right, hitNormal)) as Transform;
               Destroy(hitParticle.gameObject, 1f);
          }

          Transform clone = Instantiate(MuzzleFlashPrefab, firePoint.position, firePoint.rot

ation) as Transform;
          clone.parent = firePoint;
          float size = Random.Range(0.6f, 0.9f);
          clone.localScale = new Vector3(size, size, size);
          Destroy(clone.gameObject, 0.02f);

          //Shake the camera
          camShake.Shake(camShakeAmt, camShakeLength);

          //Play shoot sound
          audioManager.PlaySound(weaponShootSound);
     }
}

Show more replies
  • Liked by
Reply
Cancel
0 on December 3, 2017
  • Liked by
Reply
Cancel
7 on December 4, 2017

Your weapon variable never gets set in the first script you posted

on December 4, 2017

I thought that what I did there was reference the “Weapon” script so I could set the “fireRate” from the”Weapon” script equal to the “weaponFireRate” in the “PlayerStats” script?

Guru
on December 4, 2017

Nope that’s not how it works

 

on December 4, 2017

If that wasn’t what I was supposed to do, can you tell what I need to do? I’m pretty new to Unity. How do I set the weapon variable in the “PlayerStats” script?

on December 4, 2017

Do you just change “Weapon weapon;” to “private Weapon weapon;” like I did in the “UpgradeMenu” script? If not, what do I do?

Guru
on December 5, 2017

Google is a really good thing to use

on December 6, 2017

I’ve googled it and asked it on Stack Overflow, but then they referenced me to this link https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it?noredirect=1&lq=1 I just don’t get it. I’m newer to Unity so it doesn’t make too much sense to me. There are lots of example scripts on their, but I couldn’t find one similar to mine so that I could know exactly what to do. I understand you are trying to get me figure it out  myself so I can learn and I appreciate it, but I really don’t have to time to figure it out because it has to be done before I go to bed in 6 hours from now. Please tell me exactly what to do if you can. Sorry for the special request and thank you for your help so far.

Guru
on December 6, 2017

Google: script references in Unity
Or something similar

Show more replies
  • Liked by
Reply
Cancel

You can just add this script in all of your Start() functions in all the scrips and you will be good to go :

weapon = gameObject.GetComponent<Weapon>();
  • Liked by
Reply
Cancel