- Home /
Specifying Prefab to Instantiate
I want to be able to specify which prefab among a number of weapon prefabs I want to be instantiated, i.e. if myGun int is 1, then string weaponToInstantiate is "WeaponOne", and then later in the code, Instaniate(weaponToInstantiate). When I do this I get an error:
error CS1502: The best overloaded method match for UnityEngine.Object.Instantiate(UnityEngine.Object)' has some invalid arguments and error CS1503: Argument
#1' cannot convert string' expression to type
UnityEngine.Object'
Does anyone know how to go about this? (Note: all weapon prefabs are tagged as CurrentGun, and I did not specify position or rotation, because I want the default position and rotation of each weapon to be used)
Why not use variables?
var Wep : GameObject;
function Update(){ Instantiate(Wep, blah, blah); }
Answer by Spinnernicholas · Dec 05, 2013 at 04:35 PM
Define a Gun Factory class that has a list of all the Gun GameObjects
Using System.Collections.Generic;
public class GunsFactory : MonoBehavior
{
public List<GameObject> guns = new List<GameObject>();
public GameObject CreateGun(int gunIndex)
{
return Instantiate(guns[gunIndex]);
}
}
You will then create attach it to a game object and add all of your gun prefabs to it.
If you want to reference them by strings instead, you could use a dictionary:
Dictionary<String, GameObject> guns;
You probably want to make it a singleton so you can easily access it from anywhere, but that is a topic for another discussion.
I am a bit of a noob, where do I define the prefab? (Thanks for the help!)
A prefab is just a GameObject that you define and then move into your project assets. After it is safely stored in your assets, you can delete it from your scene all together. Then when you edit the list in the inspector, you can either hit the selector circle and find your prefab on the asset tab, or you can drag it straight from the asset browser into the inspector.
And the reason you store prefabs in your assets is so you can access them from any scene in your project.
Why am I getting this error: Assets/Scripts/GunFactory.cs(8,16): error CS0246: The type or namespace name `List' could not be found. Are you missing a using directive or an assembly reference?"? This is what I have so far:
using UnityEngine;
using System.Collections
using System.Collections.Generic;
public class GunFactory : $$anonymous$$onoBehaviour {
public List guns = new List();
public GameObject CreateGun(int gunIndex)
{
return UnityEngine.Object.Instantiate(guns[gunIndex]);
}
}
Answer by Tomer-Barkan · Dec 05, 2013 at 10:10 PM
You can put your prefabs in a folder called "Resources", and then load the prefab by its name using Resources.Load:
public void CreateGun(string gunName) {
GameObject gunPrefab = Resources.Load<GameObject>(gunName);
Instantiate(gunPrefab);
}
Make sure you create prefabs: Create a "Resources" folder in your assets. It must be named "Resources". Create a prefab for each gun you want by dragging the gun from the scene to the Resources folder in the project (See here about creating prefabs). Make sure the name of the prefab in the resources folder is the same as the name you pass to the CreateGun()
method.
This code gives me an error: error CS0308: The non-generic method `UnityEngine.Resources.Load(string)' cannot be used with the type arguments. What is that about?
That's weird... paste your code please. I've used this many times.
@gorgoroth In Resources.Load(gunName)
put ins$$anonymous$$d of gunName, "yourgun" , where yourgun is the name of the prefab gun, and keep the quotes. If you have for example a gun named RayGun, it must be in the Resources folder in your project explorer, and you must call it through Resources.Load("RayGun");
If you have your prefabs under another file, add the directory to the name. For example for a file named prefabs, (under the file Resources always) type:
Resources.Load("Prefabs/RayGun");
Answer by Mudman2999 · Dec 05, 2013 at 11:58 PM
if the other method does not work for you then you can reference this code from one of my projects. just change the if statement and the specific names. I hope that this helped I apologize for the bad formatting of the code I have never posted code in response to a question.
if (Input.GetKeyDown(KeyCode.Space)) {//fire lazer Vector3 position = new Vector3(myTransform.position.x, myTransform.position.y, myTransform.position.z); Instantiate(ProjectileFab, position,Quaternion.identity);}
Answer by Meltdown · Dec 06, 2013 at 02:03 AM
Create a prefab in the editor and place into the Assets/Resources folder. The Resources folder is a special folder that allows you to load assets at runtime.
Load the prefab using the following code...
GameObject gunPrefab = Resources.Load("yourgunPrefabName") as GameObject;
if(gunPrefab != null) GameObject.Instantiate(gunPrefab, Vector3.zero, Quaternion.Identity);
Answer by RyanZimmerman87 · Dec 07, 2013 at 12:25 AM
Depending how many guns you are going to have for the final version of your game some of these methods may be a little overkill especially if you are new to programming. All the list, dictionary, and resources stuff could be very useful but you should save that for once you are more comfortable with this stuff.
For starting a system like this I would probably do something like:
//do a Transform for the guns position and rotation when you instantiate
//this should probably be a child gameObject on your player
public Transform gunTransform;
//declare a few Game Objects at beginning of script
//each of these should be a public variable
//you can easily drag your prefabs from assets into public Game Objects in script
public GameObject gun0Object;
public GameObject gun1Object;
public GameObject gun2Object;
public GameObject gun3Object;
//create a public static int
//allows easy access to what gun is being used
//doesn't need to be public unless your other scripts should access it super easily
//for example your enemies could know how much damage to take when shot
//by checking what kind of gun you are using based on this identifier int
public static int currentGunInt;
//this system allows you to always know which gun you used last
void Start()
{
//check which gun to start with a PlayerPref
//the 0 is whatever gun you start with or being unarmed
//will only be 0 if you haven't saved anything else to this PlayerPref
//or that's the last gun you used
currentGunInt = PlayerPrefs.GetInt ("Gun Int", 0);
//now that you know which gun to use you call a function to instantiate prefab
//you can use this function at start as well as during gameplay when you switch guns
void equipGunFunction();
}
void equipGunFunction()
{
if (currentGunInt == 0)
{
PlayerPrefs.SetInt ("Gun Int", 0);
Instantiate (gun0Object, gunTransform.position, gunTransform.rotation) as GameObject;
}
else if (currentGunInt == 1)
{
PlayerPrefs.SetInt ("Gun Int", 1);
Instantiate (gun1Object, gunTransform.position, gunTransform.rotation) as GameObject;
}
//etc for all the guns
}
I think that's the easiest way to do it and you shouldn't be getting any errors keeping it simple. Hopefully I'm not just repeating what others have posted already, I didn't read everything in great detail just wanted to bust out a quick example hope that helps!
Edit: Oh and you'll want to add some more variables once you get this working if you use this. So you could have another public GameObject, PlayerPref, and public static int for the previous gun used so you could also destroy the old prefab in the same function where you create the new one. Or it could be used to toggle your 2 guns.
Your answer
![](https://koobas.hobune.stream/wayback/20220613123510im_/https://answers.unity.com/themes/thub/images/avi.jpg)