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