-1
\$\begingroup\$
private PlayerHealth ph;

void Start()
{
    ph = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerHealth>();
}

private void OnTriggerEnter2D(Collider2D other)
{
    if(other.tag == "PlayerFeet")
    {
        ph.TakeDamage();
    }
}

(My player prefab is with tag "Player")

https://prnt.sc/l4QgM7GShe3T

Error: NullReferenceException: Object reference not set to an instance of an object ThornController.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/ThornController.cs:48)

\$\endgroup\$
0

1 Answer 1

0
\$\begingroup\$

I guess line 48 refers to ph.TakeDamage() so the problem is that there is no object in your scene with the "Player" tag. Are you sure you set the tag correctly? If the problem still persists please send some screenshots (from the error, the player, etc.)

\$\endgroup\$
2
  • \$\begingroup\$ That's the problem, the player is with the tag Screeenshot: prnt.sc/CrclEhKoIRcs The command can't get the tag Player, but when i create a new tag with the name "player" and change on GameObject.FindGameObjectWithTag("player") it works, but the tag native of unity doesn't work \$\endgroup\$ Commented Feb 23, 2022 at 20:31
  • \$\begingroup\$ If there were no object with the Player tag, an exception would be thrown in Start too. If you don't get an exception in Start, then it could be the object tagged Player is found, but the first object found with that tag does not have the PlayerHealth component. FindObjectOfType<PlayerHealth> would be a better solution here than using tags. Similarly, you can replace your tag check in the trigger method with a physics layer instead, and simply skip processing any collisions that don't need to take damage, before the method is ever called. \$\endgroup\$ Commented Feb 23, 2022 at 23:40

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.