Hello! I am making a game in Unity using C# and have an enemy that needs to make the player take damage when it gets too close. The enemy will chase the player and I can make the enemy die if it gets too close to the player, but I can’t seem to make the player take damage. I’ve worked on this for over 3 hours before coming here and have tried looking through forums and videos to no avail. Any help is appreciated! Thank you!
Error I’m Getting:
Script on Enemy
using UnityEngine;
using System.Collections;
public class Target : MonoBehaviour {
public float health = 100f;
public float deathDistance = 0.5f;
public Transform thisObject;
public Transform target;
private UnityEngine.AI.NavMeshAgent navComponent;
private Player player;
public float damage = 10;
public void TakeDamage (float amount)
{
health -= amount;
if (health <= 0f)
{
Die();
}
}
void Die()
{
Destroy(gameObject);
}
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").transform;
navComponent = this.gameObject.GetComponent<UnityEngine.AI.NavMeshAgent>();
}
void Update()
{
float dist = Vector3.Distance(target.position, transform.position);
if(target)
{
navComponent.SetDestination(target.position);
}
else
{
if(target == null)
{
target = this.gameObject.GetComponent<Transform>();
}
else
{
target = GameObject.FindGameObjectWithTag("Player").transform;
}
}
if (dist <= deathDistance)
{ //Die();
if (target != null)
{
target.GetComponent<PlayerC>().TakeDamage(damage);
//Die();
}
}
}
}
Script on Player
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour {
public float health = 100f;
public void TakeDamage (float amount)
{
health -= amount;
if (health <= 0f)
{
Restart();
}
}
void Restart()
{
SceneManager.LoadScene("test1");
}
}