Question by
timmyiscool8 · Feb 22, 2019 at 01:06 AM ·
error messagepublic variable
Public variables acting like private ones!
I have two scripts, a data manager and another script. The data manager is storing a PUBLIC enemyCount integer. The other script is supposed to subtract 1 from that integer when an if statement is true. In the other script I create a private datamanager called dm. In the if statement I say dm.enemyCount -= 1; Even though the script and the integer are public, I still get a null reference exception. Thanks for the help!
Data Manager script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameDataManager : MonoBehaviour
{
public int currentEnemies; // <--- IT IS PUBLIC!
public Text enemiesLeftText;
public int currentWave;
public int waveMaxEnemies;
public Text waveText;
private EnemySpawnController esc;
// Start is called before the first frame update
void Start()
{
currentWave = 1;
waveMaxEnemies = 5;
currentEnemies = waveMaxEnemies;
}
// Update is called once per frame
void Update()
{
enemiesLeftText.text = currentEnemies + " enemies left";
waveText.text = "Wave " + currentWave;
if (currentEnemies <= 0)
{
currentWave += 1;
waveMaxEnemies += 5;
currentEnemies = waveMaxEnemies;
}
}
}
Other script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyHealthManager : MonoBehaviour
{
public int health;
private GameDataManager gdm; // <-- bringing in the data manager works fine!
private int currentHealth;
// Start is called before the first frame update
void Start()
{
currentHealth = health;
}
// Update is called once per frame
void Update()
{
if (currentHealth <= 0)
{
Destroy(gameObject);
gdm.currentEnemies -= 1; // <--- this is where the error is!
}
}
public void HurtEnemy(int damage)
{
currentHealth -= damage;
}
}
FULL ERROR MESSAGE:
NullReferenceException: Object reference not set to an instance of an object EnemySpawnController.Update () (at Assets/Scripts/EnemySpawnController.cs:25
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612192213im_/https://answers.unity.com/themes/thub/images/avi.jpg)