Home > Software engineering >  (Unity) To remove from a Transform array
(Unity) To remove from a Transform array

Time:01-02

    public Transform[] spawnPoints;
    void Awake()
    {
        spawnPoints = GetComponentsInChildren<Transform>();
    }

    public void Spawn()
    {
        GameObject enemy = GameManager.instance.objectManager.Get(GameManager.instance.objIndex);
        enemy.transform.position = spawnPoints[Random.Range(1,spawnPoints.Length)].transform.position;
       enemy.GetComponent<Enemy>().Init(GameManager.instance.spawnData[GameManager.instance.level]); 
    }

I made a monster be summoned from a specific location. I want to create a function that prevents monsters from being created in that location when destroying a specific object, but I tried Transform.RemoveAt(0) and it was impossible. Is it impossible to remove elements from an array in the form of Transform[]?

My Unity skills are very rudimentary. I tried Transform.Remove(0). But, it impossible

CodePudding user response:

I suppose you mean

spawnPoints.Remove(0);

No, it is "impossible" to remove anything from the beginning of an array, but there are numerous more or less lazy vs performant ways to do this, like:

spawnPoints = spawnPoints.Skip(1).ToArray();

Another, perhaps better way, would be to use a List instead:

 public List<Transform> spawnPoints;
 void Awake()
 {
     spawnPoints = GetComponentsInChildren<Transform>().ToList();
 }

Then you will be able to do what you tried in the first place:

spawnPoints.Remove(0);

Note that a List won't have the "Length" property. It is called "Count" instead.

CodePudding user response:

First off, use lists.

public List<Transform> spawnPoints;  

You can use Start or Awake or the Inspector to populate them. (I recommend the Inspector if you're new to coding which seems to be the case)

Because you use random points, you need to remember what index you used inorder to remove that specific one. Here is how: 

public void Spawn()
{
    GameObject enemy = GameManager.instance.objectManager.Get(GameManager.instance.objIndex);
    int posIdx= Random.Range(0,spawnPoints.Length-1);
    enemy.transform.position = spawnPoints[posIdx].transform.position;
    enemy.GetComponent<Enemy>().Init(GameManager.instance.spawnData[GameManager.instance.level]); 
    spawnPoints.RemoveAt(posIdx)
}

I added a local variable to "remember" the transform that you used, then I removed it from the array.

  • Related