@CripplingDepression

NullReferenceException: Object reference not set to an instance of an object когда запускаю методы из другого скрипта. как быть?

Это скрипт игрока:

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


ошибка:
NullReferenceException: Object reference not set to an instance of an object
HealthKit.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/MyScripts/HealthKit.cs:12)

я просто только пытаюсь использовать методы из других скриптов и мальца не понимаю.
  • Вопрос задан
  • 94 просмотра
Решения вопроса 1
vabka
@vabka
Токсичный шарпист
У вас поле playe - null.
Раз уж игрок наступает на аптечку, то его можно достать из гейм обжекта:
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);
        }
    }
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы