Home > Blockchain >  How would I get the transform of a object in a list?
How would I get the transform of a object in a list?

Time:12-07

So I want to have a list of spawn points for my enemies to spawn from. The problem is that I cant get the transform of a spawn point and I don't understand any solutions online. They will all probably have different names too (spawnInFrontOfDoor, spawnInside1) so I won't be able to use GetObjectWithTag. Are there any solutions?

CodePudding user response:

Save a list of your spawn points before hand, and then access that list later when you want to spawn in your enemies.

This is probably the most basic example.

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

public class Spawner : MonoBehaviour
{
    //If your game is not Procedurally Generated just drag and drop your spawn points onto this list.
    public List<Transform> spawnPoints;
    
    //Reference to your enemy.
    public GameObject enemy;
    
    void Start()
    {
        foreach(Transform spawn in spawnPoints)
        {
            SpawnEnemy(spawn);
        }
    }
    
    //Method to spawn your enemy at a given point.
    public void SpawnEnemy(Transform spawnPoint)
    {
        Instantiate(enemy, spawnPoint.position, spawnPoint.rotation);
    }
}

I have created a whole Enemy spawning system so if you need further detail or clarification don't be afraid to ask.

CodePudding user response:

You can add a script into each of your spawn points:

public void SpawnPoint : MonoBehaviour{
    public static List<SpawnPoints> spawnPoints = new List<SpawnPoints>();

    void Start() => spawnPoints.Add(this);
    
    public Transform GetTransform() => transform;
}

And wherever you need your list of spawn points, you can access through SpawnPoint.spawnPoints.

Example:

List<SpawnPoints> spawnPoints = SpawnPoint.spawnPoints;
Transform randomTransform = spawnPoints[Random.Range(0, spawnPoints.Count)].GetTransform();
Instantiate(enemyPrefab, randomTransform.position, Quaternion.identity);

If you want to access this list in Start method, change

void Start() => spawnPoints.Add(this);    

to

void Awake() => spawnPoints.Add(this);

and the list should be ready to use in Start.

  • Related