-2

Hi im having a problem with this i tried for 2 Days now but i don't know how to fix it. Im a beginner in C# and hope you can help me. Im trying to use a variable from another script but the console keeps sending me an error: NullReferenceException: Object reference not set to an instance of an object

PlayerCombat.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Scrips/PlayerCombat.cs:52)

public int attackDmg = 2; //Diffrent Script

public void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.tag == "Enemy")
        {
            PlayerTakeDamage(currentPlayerHp, GetComponent<Enemy>().attackDmg);
        }
    }

static void PlayerTakeDamage(int currentPlayerHp, int attackDmg)
    {
        currentPlayerHp -= attackDmg;
        if (currentPlayerHp <= 0)
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }

1 Answers1

0

The

GetComponent<Enemy>() 

is on another object, you can call it if you

1

Create a public variable and add the enemy object

public GameObject enemy;

And then after you dragged your enemy inside it in the inspector you can:

enemy.GetComponent<Enemy>()

Without problems

2

The second thing you can do is just declaring the enemy object

GameObject enemy;

And in the Start() you can

enemy = GameObject.FindGameObjectWithTag("Enemy");

But for this, you need to add a tag in the inspector for the enemy.

After this you can access the enemy as before.

Leoverload
  • 958
  • 3
  • 5
  • 19