Hello everyone,
I have this problem where this code leads to a NullReferenceException, i am new to coding in Unity, but im guessing that it isnt finding the Gameobject even tho I do have one with the exact same name. I dont know how to fix this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public int health;
public Transform target;
public float speed = 3f;
public float rotateSpeed = 0.0025f;
private Rigidbody2D rb;
public void TakeDamage(int damage)
{
health -= damage;
if (health <= 0)
{
Die();
}
}
void Die()
{
Destroy(gameObject);
}
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
if (!target)
{
GetTarget();
}
else
{
RotateTowardsTarget();
}
}
private void FixedUpdate()
{
//Move Forwards
}
private void RotateTowardsTarget()
{
Vector2 targetDirection = target.position - transform.position;
float angle = Mathf.Atan2(targetDirection.y, targetDirection.x) * Mathf.Rad2Deg - 90f;
Quaternion q = Quaternion.Euler(new Vector3(0, 0, angle));
transform.localRotation = Quaternion.Slerp(transform.localRotation, q, rotateSpeed);
}
private void GetTarget()
{
Debug.Log(target);
target = GameObject.FindGameObjectWithTag("Player").transform;
}
}
The problem occurs on the target = GameObject.FindGameObjectWithTag("Player").transform; .