- Home /
Unity Programmatically Link Prefab
Let's say I have 5 different enemy prefabs. I won't know until runtime which prefab I want to be spawning.
I know that normally I can make a public GameObject
variable that I can link to a script.
What's the best way to link the prefab programmatically to accomplish this? It doesn't seem very efficient to have multiple variables for each prefab that I have to write boiler plate code to handle each :).
Answer by Matt-Face · Dec 29, 2017 at 01:58 AM
Here is the easiest way to keep track of the enemies in your scene:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour {
public static List<Enemy> allEnemies = new List<Enemy>();
// Use this for initialization
void Start () {
allEnemies.Add(this);
}
// Update is called once per frame
void Update () {
}
}
Answer by Cherubini-Neto · Dec 29, 2017 at 01:54 AM
I would just create a public List<GameObject>
and assign them in the editor. Then you could use a loop on the list to write the code you need to handle each prefab.
Your answer
Follow this Question
Related Questions
Prefabs won't change? 1 Answer
PrefabUtility.ReplacePrefab overrides changes 0 Answers
How to update a prefab from a copy in the hierarchy 0 Answers
Reinitialize prefab 0 Answers
Suggestions for Prefabs which refer to other Prefabs 0 Answers