Answer the question
In order to leave comments, you need to log in
NullReferenceException: Object reference not set to an instance of an object when I run methods from another script. how to be?
This is the player script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public int maxHealth;
public int currentHealth;
public HealthBar healthBar;
public void TakeDamage(int damage)
{
currentHealth = currentHealth - damage;
healthBar.SetHealth(currentHealth);
}
public void ReceiveHeal(int heal)
{
currentHealth = currentHealth + maxHealth / heal;
healthBar.SetHealth(currentHealth);
}
void Start()
{
currentHealth = maxHealth;
healthBar.SetMaxHealth(maxHealth);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthKit : MonoBehaviour
{
public int heal;
public Player playe;
void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "Player"){
playe.ReceiveHeal(heal);
Destroy(gameObject);
}
}
}
Answer the question
In order to leave comments, you need to log in
Your playe field is null.
Since the player steps on the first aid kit, you can get it from the game object:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthKit : MonoBehaviour
{
[SerializeField]
private int restoresHealth;
void OnCollisionEnter2D(Collision2D collision)
{
var player = collision.gameObject.getComponent<Player>();
if(player != null){
player.ReceiveHeal(restoresHealth);
Destroy(gameObject);
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question