Hello, I´m new to Unity and C# and I run into a big problem(for me) a couple of hours ago. I have tried to fix it but it doesn´t work. So I am trying to make a health system for the player, and it, as I said, doesn’t want to work. I have a playerHealth variable on the PlayerController script and as you can see I want to get the PlayerDam number from the EnemyFollow script after that the enemy has got close enough to the player. And I have used else before, but I changed it to another if statement just to see if that fixed anything. The part with that the EnemyFollow understands that it is close enough works good, and the Debug.Log says Damage Taken, but apparently, the Getcomponents doesn´t work and I get an error:
NullReferenceException: Object reference not set to an instance of an object EnemyFollow.Update () (at Assets/scripts/EnemyFollow.cs:31.
Please help, somebody!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyFollow : MonoBehaviour {
public float Speed;
public float stoppingDistance;
public float offset;
public int playerDam;
private Transform Target;
void Start()
{
Target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
void Update()
{
if(Vector2.Distance(transform.position, Target.position) > stoppingDistance)
{
transform.position = Vector2.MoveTowards(transform.position, Target.position, Speed * Time.deltaTime);
}
if (Vector2.Distance(transform.position, Target.position) < stoppingDistance)
{
Debug.Log("Damage taken");
GetComponent<PlayerController>().DamagePlayer(playerDam);
}
Vector3 difference = Target.position - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
}
}
- using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
public float speed;
public int playerHealth;
private Rigidbody2D rb;
private Vector2 moveVelocity;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
Vector2 moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
moveVelocity = moveInput.normalized * speed;
}
private void FixedUpdate()
{
rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
}
public void DamagePlayer(int playerDam)
{
playerHealth -= playerDam;
Debug.Log(playerHealth);
}
}