Home > Net >  How do make the gameobject to target the array gameobject?
How do make the gameobject to target the array gameobject?

Time:11-16

The program is Unity and I'm trying to make a bullet that follows the enemy. But the enemy gameobject is an array(they spawn as much as the wave's number) so I'm trying to instantiate the bullet as much as the wave's number and target each of the enemy.

The reason I'm using array is because the enemy has two types: 0 = enemy, 1 = fast enemy

public class SpawnManager : MonoBehaviour
{
    public GameObject powerupPrefab;
    public GameObject[] enemyPrefab;
    public GameObject bullet;
    public GameObject player;

    private float spawnRange = 9;
    public float bulletSpeed;

    public int enemyCount;
    public int waveNumber;
    
    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        enemyCount = GameObject.FindGameObjectsWithTag("Enemy").Length;

        if (enemyCount == 0)
        {
            waveNumber  ;
            SpawnEnemyWave(waveNumber, Random.Range(0, enemyPrefab.Length));
        }

        for (int i = 0; i < waveNumber; i  )
        {
            Instantiate(bullet, bullet.transform.position, bulletRotation);
            BulletMove();
        }
        
    }

    void BulletMove(GameObject[] enemy)
    {
        Vector3 lookDirection = (enemy.transform.position - transform.position).normalized;
        bullet.GetComponent<Rigidbody>().AddForce(lookDirection * bulletSpeed);
    }

    void SpawnEnemyWave(int enemiesToSpawn, int index)
    {
        for (int i = 0; i < enemiesToSpawn; i  )
        {
            index = Random.Range(0, enemyPrefab.Length);
            Instantiate(enemyPrefab[index].gameObject, GenerateSpawnPosition(), enemyPrefab[index].gameObject.transform.rotation);
        }
    }

I expected this code to make the each missiles target each enemy and follow the enemy but I can't figure it out how to make each missiles target each enemy in an array. But the error CS0103, CS7036 and CS1061 shows up.

CodePudding user response:

There are some obvious short-sights here but I will try to give you a hand.

First you dont have an Enemy that's an array, you have an array of Enemies. Meaning you can store your enemy GameObjects in a GameObject[], so you cannot access GameObject functions in a GameObject[] you need to iterate or access each GameObject in the array arbitrarily.

Then Second you cannot expect your code to work if you do not complete it, there are missing attributes and variables, that is fine while you are doing the sketch but now you are confused about your code not running while your code is not fully implemented, you need to check the warnings and errors on your editor, obviously code error CS0103 says The name 'enemyCount' does not exist in the current context so you either write it wrong, you try to access from other script without referencing, or proper access, or you didn't create in the first place. Have a look here for c# basics and here for unity basics

I tried to fill in some gaps in your code but this is by no means a working script, here are some keys:

  • Dont instantiate every frame a bullet per enemy, set a timer or an input button to trigger the firing;
  • Keep track of the enemies on a list and remove them from the list as they die so you can save some performance;
  • And finally, Add some logic to store what enemy each bullet is targeting so it can follow the same enemy, that can be done with a dictionary, where you have a key enemy with a value bullet or list of bullets;

It can get quite messy at first, so take it easy and write your code one step at the time, see the error description, search for it if you dont understand.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnManager : MonoBehaviour
{
    public GameObject powerupPrefab;
    public GameObject[] enemyPrefabs;//plural for collections
    public GameObject bullet;
    public GameObject player;

    private float spawnRange = 9;
    public float bulletSpeed;

    public int enemyCount;
    public int waveNumber;

    // Update is called once per frame
    void Update()
    {
        GameObject[] enemies;//added GameObject array to store the enemies
        enemies = GameObject.FindGameObjectsWithTag("Enemy"); //stored the enemies Array
        //I think you would be better keeping score of the Enemies as they die instead of searching for them every frame

        enemyCount = enemies.Length; //store the lenght of the enemies array

        if (enemyCount == 0)
        {
            waveNumber  ;
            SpawnEnemyWave(waveNumber, Random.Range(0, enemyPrefabs.Length));
        }
 
        //this will create 1 bullet per enemy every frame
        for (int i = 0; i < waveNumber; i  )
        {
            Instantiate(bullet, bullet.transform.parent.transform.position, Quaternion.identity); //get the position of the parent instead of the transform and removed the rotation
            BulletMove(enemies);//added enemies to the method
        }

    }

    void BulletMove(GameObject[] enemies)
    {
        foreach (var enemy in enemies) //iterate through the array to accees each enemy
        {
            Vector3 lookDirection = (enemy.transform.position - transform.position).normalized;
            bullet.GetComponent<Rigidbody>().AddForce(lookDirection * bulletSpeed);
        }
    }

    void SpawnEnemyWave(int enemiesToSpawn, int index)
    {
        for (int i = 0; i < enemiesToSpawn; i  )
        {
            //you are sending the index so no need to set it here as well
            Instantiate(enemyPrefabs[index], GenerateSpawnPosition(), enemyPrefabs[index].transform.rotation);//remove the .gameobject since enemy prefabs are gameobjects
        }
    }

    private Vector3 GenerateSpawnPosition()
    {
        //you need to create this logic yet
/*        return new Vector3(
            Random.Range(enemySpawnBounds.x),
            Random.Range(enemySpawnBounds.y),
            Random.Range(enemySpawnBounds.z));*/
        throw new System.NotImplementedException();
    }
}

  • Related