Can't access player position from another script

So right now im trying to make an enemy on a 2D plane check to see if the player.transform.position.x is either > or < the transform.position.x of the object. If so, it will either add a force negative or positive on the x value of the enemy to move the enemy towards the player. Except when i try this, the editor says that there is a null reference to the player and that i cant do player.transform.position.x. If anyone knows what im doing wrong, please tell me. All answers are appreciated, thanks

Ignore “_isHopping”

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    private Rigidbody2D rb;

    private Player player;

    [SerializeField]
    private bool _isHopping = false;
    [SerializeField]
    private float _jumpForce = 430.0f;
    [SerializeField]
    private float _sideForce = 200.0f;

    // Start is called before the first frame update
    void Start()
    {
        rb = gameObject.GetComponent<Rigidbody2D>();
        player = gameObject.GetComponent<Player>();

        StartCoroutine(EnemyAction());
    }

    //spin when jump
    //on collission with player, die and drop coins

    IEnumerator EnemyAction()
    {
        while (true)
        {
            _isHopping = false;
            yield return new WaitForSeconds(3.0f);
            _isHopping = true;

            rb.AddForce(Vector3.up * _jumpForce);

            float playerPosX = player.transform.position.x;

            if (playerPosX > transform.position.x)
            {
                rb.AddForce(Vector3.right * _sideForce);
            }
            else if (playerPosX < transform.position.x)
            {
                rb.AddForce(Vector3.right * -_sideForce);
            }

            yield return new WaitForSeconds(0.8f);
        }
    }
}

gameObject.GetComponent() looks at the same gameobject that your Enemy script is on. I doubt you have both the enemy and the player script on the same gameobject in the scene.

If you only have one Player script in the scene, you can just FindObjectOfType instead. But what might be better is to have a manager script in the scene that references your player. Then your enemy scripts access the player through that Manager script which could be a singleton

Alright it works great! Also wait so, is FindObjectOfType referencing the Player gameobject or is it getting the component through the player?

FindObjectOfType ransacks the entire scene looking for an instance of the Player Monobehavior… the first one it finds it returns. If there are none it returns null. This is not a particularly performant function and is ideally only called once at the start of a scene, traditionally in Start().

Ahh ok thanks for the help!