I have the following to scripts. One is attached to the AttackState within the animator, and the other is attached to an empty gameobject called PlayerManager. The goal is when the attack method is called and the player is within a certain spherical distance of the enemy, the player will take damage that is reflected in the UI. The problem is that while all is working, the first time the enemy attacks the player the number flys into the thousands. If I try to use lower case playerManager to utilize the reference to the instance, I get an error. I’m new to this whole thing obviously, so any help on implementing a method that keeps the core of this intact I’d appreciate it.
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class PlayerManager : MonoBehaviour
{
public static int playerHP = 100;
public TextMeshProUGUI playerHPText;
public static bool isGameOver;
void Start()
{
}
// Update is called once per frame
void Update()
{
playerHPText.text = "+" + playerHP;
if (isGameOver)
{
//display game over screen
}
}
public static void TakeDamage(int damageAmount)
{
playerHP -= damageAmount;
if (playerHP <= 0)
isGameOver = true;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AttackState : StateMachineBehaviour
{
Transform player;
PlayerManager playerManager;
public float radius = 3;
public int damageAmount = 15;
// OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
player = GameObject.FindGameObjectWithTag("Player").transform;
playerManager = player.GetComponent<PlayerManager>();
}
// OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
animator.transform.LookAt(player);
float distance = Vector3.Distance(player.position, animator.transform.position);
if (distance > 3.5f)
animator.SetBool("isAttacking", false);
Collider[] colliders = Physics.OverlapSphere(animator.transform.position, radius);
foreach (Collider nearbyObject in colliders)
{
PlayerManager.TakeDamage(damageAmount);
}
}
// OnStateExit is called when a transition ends and the state machine finishes evaluating this state
override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
}
// OnStateMove is called right after Animator.OnAnimatorMove()
//override public void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
//{
// // Implement code that processes and affects root motion
//}
// OnStateIK is called right after Animator.OnAnimatorIK()
//override public void OnStateIK(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
//{
// // Implement code that sets up animation IK (inverse kinematics)
//}
}