When I used Rick’s version of the method in which it updates to check if currentTarget is available it does not work and continues to stay still:
public class Attacker : MonoBehaviour
{
[Range(0f, 5f)]
float currentSpeed = 1f;
GameObject currentTarget;
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector2.left * currentSpeed * Time.deltaTime);
UpdateAnimationState();
}
private void UpdateAnimationState()
{
if (!currentTarget)
{
GetComponent<Animator>().SetBool("isAttacking", false);
}
}
public void SetMovementSpeed(float speed)
{
currentSpeed = speed;
}
public void Attack(GameObject target)
{
GetComponent<Animator>().SetBool("isAttacking", true);
currentTarget = target;
}
public void StrikeCurrentTarget(float damage)
{
if (!currentTarget)
{
return;
}
Health health = currentTarget.GetComponent<Health>();
float healthCount = currentTarget.GetComponent<Health>().healthCount;
if (health)
{
health.DealDamage(damage);
}
}
}
but if I used my version which checks on the currentTarget’s health on each strike frame it works fine:
public class Attacker : MonoBehaviour
{
[Range(0f, 5f)]
float currentSpeed = 1f;
GameObject currentTarget;
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector2.left * currentSpeed * Time.deltaTime);
}
public void SetMovementSpeed(float speed)
{
currentSpeed = speed;
}
public void Attack(GameObject target)
{
GetComponent<Animator>().SetBool("isAttacking", true);
currentTarget = target;
}
public void StrikeCurrentTarget(float damage)
{
if (!currentTarget)
{
return;
}
Health health = currentTarget.GetComponent<Health>();
float healthCount = currentTarget.GetComponent<Health>().healthCount;
if (health)
{
health.DealDamage(damage);
}
if(healthCount <= 0)
{
GetComponent<Animator>().SetBool("isAttacking",false);
currentSpeed = 1f;
}
}
}
Why is this? Am I missing something?
here’s my script for the lizard we made or as I called it “BlueOcto”
public class BlueOcto : MonoBehaviour
{
GameObject otherObject;
private void OnTriggerEnter2D(Collider2D othercollider)
{
otherObject = othercollider.gameObject;
if(otherObject.GetComponent<Defender>())
{
GetComponent<Attacker>().Attack(otherObject);
}
}
}