So i am recreating space invaders as part of my University project. I have the player firing but now i want to reuse the same script for the enemies. I have it all figured out pretty much except for replacing firing button with a random timer. Ideally i would want to be able to manipulate the chance any individual enemy will fire until i feel i hit the right amount, not too hard and not too easy to dodge. Here’s the code i have for the player firing.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerShooting : MonoBehaviour
{
public Transform PlayerGun;
public GameObject PlayerBullet;
// Update is called once per frame
void Update()
{
if(Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
Instantiate(PlayerBullet, PlayerGun.position, PlayerGun.rotation);
}
}
Additionally i have a bit of a problem, if anyone can figure it out. My bullet entity is supposed to self destruct upon hitting the first enemy but instead it keeps going trough all 3 rows. Here’s the bullet code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public float speed = 20f;
public Rigidbody2D rb;
public int damage = 1;
// Start is called before the first frame update
void Start()
{
rb.velocity = transform.up * speed;
}
void OnTriggerEnter2D(Collider2D hitInfo)
{
EnemyDestroy enemyDestroy = hitInfo.GetComponent<EnemyDestroy>();
if (enemyDestroy != null)
{
enemyDestroy.TakeDamage(damage);
}
Destroy(gameObject);
}
}
And here’s the code for the enemies when they self destruct upon being hit:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyDestroy : MonoBehaviour
{
public int health = 1;
public GameObject deathEffect;
public void TakeDamage (int damage)
{
health -= damage;
if (health <= 0)
{
Die();
}
}
void Die()
{
Instantiate(deathEffect, transform.position, Quaternion.identity);
Destroy(gameObject);
}
}
I really can’t figure out why enemies get destroyed but bullets don’t.
Thanks in advance.