Hi, I’m so new to coding and making a game. I’m making a Space Invaders game using Unity 2D. Everything is fine, but when I shoot a bullet by tapping the space button, the bullets are released and when they hit the aliens, they disappear, but they are unable to kill the aliens. Can you please help me with this issue?
MoveAliens script:
using UnityEngine;
using UnityEngine.SceneManagement;
public class MoveAliens : MonoBehaviour
{
private float Speed = 2.0f;
private float speedIncrease = 0.5f;
public bool directionRight = true;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (directionRight == true)
{
transform.Translate(Vector3.right * Time.deltaTime * Speed);
}
else {
transform.Translate(Vector3.left * Time.deltaTime * Speed);
}
if(transform.position.x > 14)
{
transform.position += new Vector3(0, -1, 0);
directionRight = false;
}
if(transform.position.x < 0)
{
transform.position += new Vector3(0, -1, 0);
directionRight = true;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
SceneManager.LoadScene(0);
}
public void Die()
{
GetComponent<SpriteRenderer>().enabled = false;
GetComponent<Collider2D>().enabled = false;
}
public void Respawn()
{
GetComponent<SpriteRenderer>().enabled = true;
GetComponent<Collider2D>().enabled = true;
}
}
RockeProjectile script:
using UnityEngine;
public class RocketProjectile : MonoBehaviour
{
private float speed = 5.0f;
// Start is called before the first frame update
void Start()
{
Destroy(gameObject, 3);
}
private void Update()
{
if (transform.position.y < 5)
{
transform.position += Vector3.up * Time.deltaTime * speed;
}
else
{
Destroy(gameObject);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
var enemy = collision.collider.GetComponent<MoveAliens>();
enemy?.Die();
Destroy(gameObject);
}
}