C
C
CripplingDepression2021-08-06 01:05:14
Unity
CripplingDepression, 2021-08-06 01:05:14

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);
    }
}


and these are first aid kits:

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);
        }
    }
}


error:
NullReferenceException: Object reference not set to an instance of an object
HealthKit.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/MyScripts/HealthKit.cs:12

)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-08-06
@CripplingDepression

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 question

Ask a Question

731 491 924 answers to any question