Bank Script not working

Getting this error everytime enemy is reaches the end. Plus starting and current balance is not updating.

Here is the Bank Script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bank : MonoBehaviour
{
[SerializeField] int startingBalance = 500;
[SerializeField] int currentBalance;
public int CurrentBalance{get { return currentBalance; } }

void Awake()
{
startingBalance = currentBalance;
}
public void Deposit(int amount)
{
currentBalance += Mathf.Abs(amount);
}
public void Withdrawal(int amount)
{
currentBalance -= Mathf.Abs(amount);
}
}


Here is the EnemeyMover Script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyMover : MonoBehaviour
{
[SerializeField] List path = new List();
[SerializeField] [Range(0f,5f)] float enemySpeed = 1f;
Enemy enemy;

void OnEnable()
{
FindPath();
ReturnToStart();
StartCoroutine(PrintWayPointName());
}

void Start()
{
  enemy = GetComponent<Enemy>();
}

void FindPath()
 {
   path.Clear();
  
   GameObject[] waypoints = GameObject.FindGameObjectsWithTag("Path");

   foreach(GameObject waypoint in waypoints)
    {
      path.Add(waypoint.GetComponent<WayPoint>());
    }
  }

void ReturnToStart()
{
    transform.position = path[0].transform.position;
}

IEnumerator PrintWayPointName()
{
foreach(WayPoint wayPoint in path)
{
Vector3 startPosition = transform.position;
Vector3 endPosition = wayPoint.transform.position;
float travelPercent = 0f;

   transform.LookAt(endPosition);
  
   while(travelPercent < 1f)
    {
     travelPercent += Time.deltaTime * enemySpeed;
     transform.position = Vector3.Lerp(startPosition, endPosition, travelPercent);
     yield return new WaitForEndOfFrame();
    }
  }
 gameObject.SetActive(false);
 enemy.StealGold();

}
}


Here is the Enemy Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
[SerializeField] int goldReward = 50;
[SerializeField] int goldPenalty = 50;
Bank bank;
void Start()
{
bank = FindObjectOfType();
}

public void RewardGold()
{
if(bank = null){return;}
bank.Deposit(goldReward);
}

public void StealGold()
{
if(bank = null){return;}
bank.Withdrawal(goldPenalty);
}
}

Hi Varun,

NullReferenceException means that a reference (“link”) to an instance is missing. Double click on the error message to see to which line in your code it is referring. If you exposed a field in the Inspector, make sure that it’s not empty.

Have you already compared your code to the Lecture Project Changes which can be found in the Resources of this lecture?


See also:

Ohh restarted unity and now it works. Sorry for the trouble.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms