Hello, I am a coding novice so I am sorry if this is something that should be easily fixed, but I was taking a Udemy course Unity 2d game development, and I am on lecture 6 near the end, and I am having trouble making the bullet actually hit enemies. On Udemy it is lesson 101 where we program the bullet behavior. For some reason the script recognizes that bullets should disappear when they hit walls, but not enemies. This is the code for my bullet script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
[SerializeField] float bulletSpeed = 20f;
Rigidbody2D rb2d;
PlayerController player;
float xSpeed;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
player = FindObjectOfType<PlayerController>();
xSpeed = player.transform.localScale.x * bulletSpeed;
}
// Update is called once per frame
void Update()
{
rb2d.velocity = new Vector2(xSpeed, 0f);
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Enemy")
{
// bullets should destroy enemies
Destroy(other.gameObject);
}
// Bullets get destroyed when they hit a wall
Destroy(gameObject);
}
void OnCollisionEnter2D(Collision2D other)
{
Destroy(gameObject);
}
}
Can anybody tell me what I did wrong? If needed I can provide the zip file for my game.
Thanks