Enemy object does not enter collide and trigger functions
Hello, I just started learning C# and unity. I'm practicing what I've learned. What kind of mistake could I have made in this script? My enemy object is moving towards to player but dont attack when colliders collide and when ı shoot and send bullets from my player, the enemy does not affected.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
private Transform playerPos;
private bool isWalk = false;
private bool isAttack = false;
public float speed;
public int health = 3;
public Animator animator;
// Start is called before the first frame update
void Start()
{
playerPos = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
// Update is called once per frame
void Update()
{
if (transform.position != playerPos.position)
{
Walk();
}
if (health <= 0)
{
Destroy(gameObject);
}
}
void OnCollisionStay(Collision col)
{
if (col.gameObject.CompareTag("Player"))
{
Debug.Log("player col");
Attack();
}
}
/* void OnCollisionExit(Collision col)
{
if (col.gameObject.CompareTag("Player"))
{
isAttack = false;
Walk();
}
} */
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Bullet"))
{
Debug.Log("bullet col");
health--;
}
}
private void Walk()
{
transform.position = Vector2.MoveTowards(transform.position, playerPos.position, speed * Time.deltaTime);
isWalk = true;
WalkAnim();
}
private void Attack()
{
isAttack = true;
AttackAnim();
}
private void AttackAnim()
{
if (isAttack)
{
animator.SetBool("isAttack", true);
}
else
{
animator.SetBool("isAttack", false);
}
}
private void WalkAnim()
{
if (isWalk)
{
animator.SetBool("isWalking", true);
}
else
{
animator.SetBool("isWalking", false);
}
}
}
I am sure that my player and my enemy have rigidbody and collider and have true tags. Hint for experts: enemy object still walking when ıt comes to the player's pos.
Answer by Pathojen · Dec 07, 2021 at 07:45 AM
By the looks of it, I would say it's because you're using transform.position to move. An alternative would be to use transform.Translate(Vector 3 direction).
Your answer
Follow this Question
Related Questions
Collider's codes works, while dont colliding.. 1 Answer
Enemy direction going crazy after collision 1 Answer
Player cannot destroy enemy 1 Answer
Enemy is not taking damage! 0 Answers
Player takes damage through collider tag 0 Answers