hiya, this is my first ever unity game and so im working off of a lot of different tutorials to learn. after trying to implement enemy death animations i found that no matter how i tried coding it the game seemed to just break just before the enemy was meant to die. originally i thought it had something to do with my animation or the way i coded my enemy but unity kept saying that the issue was with the bullet script.
this is my error message:
this is my bullet script:
public class BulletScript:
private Vector3 mousePos;
private Camera mainCam;
private Rigidbody2D rb;
public float force;
void Start()
{
mainCam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
rb = GetComponent<Rigidbody2D>();
mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = mousePos - transform.position;
Vector3 rotation = transform.position - mousePos;
rb.velocity = new Vector2(direction.x, direction.y).normalized*force;
float rot = Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, rot + 90);
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.TryGetComponent<Enemy>(out Enemy enemyComponent))
{
enemyComponent.TakeDamage(1);
Destroy(gameObject);
}
}
and below is my enemy script:
private Animator Anim;
private string WALK_ANIM = "Gnome Anim";
private SpriteRenderer sr;
GameObject obj;
private float movementX;
[SerializeField] float Health, maxHealth = 3f;
[SerializeField] float speed = 10f;
Transform target;
Vector2 moveDirection;
private Rigidbody2D myBody;
private void Awake()
{
myBody = GetComponent<Rigidbody2D>();
sr = GetComponent<SpriteRenderer>();
}
private void Start()
{
Health = maxHealth;
target = GameObject.Find("Player").transform;
}
public void TakeDamage(float damage)
{
Health -= damage;
if (Health <= 0)
{
Anim.SetTrigger("dead");
Destroy(gameObject, 2);
}
}
void Update()
{
if (target)
{
Vector3 direction = (target.position - transform.position).normalized;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
moveDirection = direction;
}
}
private void FixedUpdate()
{
if (target)
{
myBody.velocity = new Vector2(moveDirection.x, moveDirection.y) * speed;
}
}
void AnimateEnemy()
{
Anim.SetBool(WALK_ANIM, true);
if (movementX > 0)
{
sr.flipX = false;
}
//going left
else if (movementX < 0)
{
sr.flipX = true;
}
}
i appreciate any help anyone can give me as i am completely lost and i couldnt find any helpful videos online or any issues from other people, ive probably just done something really silly and havent realised it lol.