Search Unity

Accessing script after using findobjectwithtag

Discussion in 'Scripting' started by liquidsht, Jun 8, 2020.

  1. liquidsht

    liquidsht

    Joined:
    Jun 4, 2020
    Posts:
    49
    Hi I am trying to access the PlayerHealth script under the player in my game from the enemies but I keep getting the Null Reference Exception error :

    Code (CSharp):
    1. public class HornedDemonTouchDamage : MonoBehaviour
    2. {
    3.   public GameObject player;
    4.   PlayerHealth playerHealth;
    5.  
    6. void Start()
    7.     {      
    8.           playerHealth = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerHealth>();
    9.      }
    10. }
    is this correct way to do it? Thanks!
     
  2. brigas

    brigas

    Joined:
    Oct 4, 2014
    Posts:
    522
    your syntax seems correct, you probably dont have your player tagged as "Player"

    you can also use
    Code (CSharp):
    1. GameObject.Find("Player").GetComponent<PlayerHealth>();
    if the name of your player object is - Player
     
  3. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    If there is only one in the scene, you could use
    Code (CSharp):
    1. playerHealth = FindObjectOfType<PlayerHealth>();
    instead and then it doesn't matter what the gameobject name is.
     
  4. dahiyabunty1

    dahiyabunty1

    Joined:
    Jan 22, 2020
    Posts:
    68
    make it public and then play the game. then you can see if player health is filled or not and then post again...
     
  5. liquidsht

    liquidsht

    Joined:
    Jun 4, 2020
    Posts:
    49
    Thanks! still not sure why findobjectwithtag doesnt work thou. The player is tagged and the PlayerHealth script is running but FindObjectOfType is working now.