Instantiate directly from Project/Prefabs


I’m a beginner programmer making a vertical shmup game and I’m trying to create an efficient method for instantiating enemies into the scene. I’m working on extending the editor to make the inspector more versatile for what I’m doing. Ideally, I’d like to have drop down lists for the user to be able to select the enemy type, weapon type, etc., by using enumerators and having the script search for the prefab that corresponds to that selection from the project/prefabs folder.

I understand that the most common and practical way of instantiating a prefab is to initialize a GameObject variable and then drop the prefab into that slot in the inspector, but I really think that a drop down list would look more polished and be a little easier of a workstream for the level designers.

Okay, so the approach that I’ve tried to get this to work is admittedly very crude. I’ve tried to create an empty GameObject called “ObjectLibrary” with an attached script that stores all the prefabs, called “ObjectLibrary.js.” My line of reasoning was that I could let the script attached to the enemy search for the GameObject it needs from the ObjectLibrary. However, when I try to retrieve the needed GameObject, Unity returns ". . . ‘EnemySmall’ is not a member of ‘UnityEngine.GameObject’. "

If you see anything wrong with my code, please let me know. Otherwise, if this approach is absurd, please enlighten me on a better method to get the desired results! Either way, thank you so much for your help!

Here is the code attached to the enemy:

#pragma strict

enum Type {Small, Big}
enum Weapon {Yellow, Red}

var EnemyType : Type;
var WeaponType : Weapon;
var Speed : float;
var Enemy_Ship_Health : float = 100.0;
var ScoreValue : int = 100;
var SpawnTime : int = 2;

private var ObjectLibrary : GameObject;
private var EnemyShip : GameObject;
private var Clone : GameObject;

function Start () {

	ObjectLibrary = GameObject.Find("ObjectLibrary");

		if(EnemyType == Type.Small){
			EnemyShip = ObjectLibrary.EnemySmall;

//"If the user selected a small ship type, then look to ‘ObjectLibrary’ to see what GameObject is defined as ‘EnemySmall’

			yield WaitForSeconds(SpawnTime);
			Clone = Instantiate(EnemyShip, transform.position, transform.rotation);
			Clone.transform.parent = gameObject.transform;


And here is the code attached to the GameObject called “ObjectLibrary” (just simply variable declarations for the GameObjects that I’m trying to reference):

#pragma strict

var EnemySmall : GameObject;
var EnemyBig : GameObject;
var RedProjectile : GameObject;
var YellowProjectile : GameObject;

Again, any help would be very much appreciated!

Your ObjectLibrary is of the type gameObject and is not your script.

var script = ObjectLibrary.GetComponent(ScriptName);

to get your script, then use