Scripts working in Editor, but not in build
Everything works great in the editor, but as soon as I try it in the build, some of the controls don't work, such as the Jump mechanic using the spacebar. It also gives me the following error: "NullReferenceException: Object reference not set to an instance of an object Player.Update () (at Assets/Scripts/Player/Player.cs:44)". Please help me! This project is due in less than a week!!
Here's the script that tracks the player's health and what not:
{
public Collision2D collision;
GameObject playerObject;
Collider2D player;
Rigidbody2D player_rb;
readonly AudioSource gg_player;
[Header("Enemy Hook Config")]
public Rigidbody2D nearestEnemy;
public Transform nearestEnemyTransform;
[Header("Health Tracking")]
public HealthBar healthBar;
public Slider healthSlider;
public int maxHealth = 100;
public int currentHealth;
private void Start()
{
healthSlider = GetComponent<Slider>();
// Get the nearest enemy transform and collider
nearestEnemyTransform = FindObjectOfType<EnemyAI>().GetComponent<Transform>();
nearestEnemy = GetComponent<Rigidbody2D>();
// Set player health data
healthBar.SetMaxHealth(maxHealth);
healthBar.SetHealth(currentHealth);
currentHealth = maxHealth;
}
void Update()
{
if (collision.gameObject.CompareTag("Enemy"))
{
TakeDamage(10);
}
if (currentHealth <= 0)
{
KillPlayer();
}
else
{
return;
}
}
void KillPlayer()
{
SceneManager.LoadScene("GameOver");
}
//public void OnCollisionEnter2D()
//{
// if(collision.collider.gameObject.CompareTag("Enemy"))
// {
// TakeDamage(10);
// }
//}
void TakeDamage(int damage)
{
currentHealth -= damage;
healthBar.SetHealth(currentHealth);
}
}
Answer by Pathojen · Apr 28 at 09:30 PM
Make Player public, like this.
public GameObject PlayerObject;
Then drag and drop the player into the slot with PlayerObject on it.
Alternatively, in Start, type:
PlayerObject = GameObject.Find("PlayerObject");
Edit: Change Player to player. In the update.
Yes. I even replaced the code with what you suggested.
OK. Do you have a space between player and Object? Should be one word.
Oh, good grief. The error says Player, but the Collider2D is player.
Yeah. I've been trying everything I know of so far.
Answer by Eddie21uk · May 22 at 10:54 PM
Hi A bit late try:
OnCollisionEnter(collision.gameobject.CompareTag("Enemy")) { TakeDamage(10); }
not:
void Update()
{
if (collision.gameObject.CompareTag("Enemy"))
{
TakeDamage(10);
}