0

I would like to create a Game which is like Slither.io and would want the enemy to shoot the nearest enemy and only shoots once and then stops. With some help I researched about looping but I'm completely Lost and would like some assistance Thank you

public class RandomAIProjectile
{
    private GameObject[] target;
    
    public float speed;
    
    Rigidbody2D bulletRB;
    
    public GameObject explosionEffect;
    
    // Find Targets Section.
    void Start () 
    {
        if (target == null)
            target = GameObject.FindGameObjectsWithTag("Player");
        
        for (int i = 0; i < target.Length; i++) 
        {
            bulletRB = GetComponent<Rigidbody2D> ();
            
            Vector2 moveDir = (target[i].transform.position - transform.position).normalized * speed;
            
            bulletRB.velocity = new Vector2 (moveDir.x, moveDir.y);
            
            Destroy (this.gameObject, 2);
        }
        
    }
    
    private void OnTriggerEnter2D(Collider2D other)
    {
        // Decoy Script To Destroy Players.
        if (other.gameObject.GetComponent<BlackthronpodDiePlayer>() != null)
        {
            Destroy (other.gameObject);
            Destroy (gameObject); 
        }
        // Damage Effect.
        if (other.gameObject.tag == "Player") {
            Instantiate (explosionEffect, transform.position, Quaternion.identity);
            Destroy(gameObject);
        }
        // Player (Bullet) Destroy Enemy.
        if (other.CompareTag ("Bullet"))
        {
            Destroy (other.gameObject);
            Destroy (gameObject); 
        }
        
        
    }
}
dkackman
  • 15,179
  • 13
  • 69
  • 123
  • I'm using Unity 2017 * – Nathan Kumwenda Jan 30 '22 at 17:30
  • Split up your problem and search for answers individually for e.g. [What is the most effective way to get closest target](https://stackoverflow.com/questions/33145365/what-is-the-most-effective-way-to-get-closest-target) and [How to make the script wait/sleep in a simple way in unity](https://stackoverflow.com/questions/30056471/how-to-make-the-script-wait-sleep-in-a-simple-way-in-unity) – derHugo Jan 30 '22 at 17:37

1 Answers1

0

Having this in the start method will only run it once the object is initialaized you would want to include a void Update() method to make the object fire every frame. Then you could add something like a bool to say that it has fired.

if(fired)
{ //do nothing}    
Palisar
  • 69
  • 1
  • 5