Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by gorgoroth · Dec 05, 2013 at 03:52 PM · instantiateprefabweapon

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)

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image applejuices · Dec 05, 2013 at 03:53 PM 0
Share

Why not use variables?

var Wep : GameObject;

function Update(){ Instantiate(Wep, blah, blah); }

5 Replies

· Add your reply
  • Sort: 
avatar image
1

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.

Comment
Add comment · Show 11 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image gorgoroth · Dec 05, 2013 at 05:11 PM 0
Share

I am a bit of a noob, where do I define the prefab? (Thanks for the help!)

avatar image Spinnernicholas · Dec 05, 2013 at 05:23 PM 0
Share

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.

avatar image Spinnernicholas · Dec 05, 2013 at 05:25 PM 0
Share

And the reason you store prefabs in your assets is so you can access them from any scene in your project.

avatar image gorgoroth · Dec 05, 2013 at 05:45 PM 0
Share

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]);
     }
 
 }
 
avatar image Spinnernicholas · Dec 05, 2013 at 07:15 PM 0
Share

Sorry, that was a typo on my part, I fixed it.

Show more comments
avatar image
1

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.

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image gorgoroth · Dec 06, 2013 at 12:21 AM 0
Share

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?

avatar image Tomer-Barkan · Dec 06, 2013 at 04:48 AM 0
Share

That's weird... paste your code please. I've used this many times.

avatar image Raiden-Freeman · Dec 06, 2013 at 11:40 PM 0
Share

@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");

avatar image
0

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);}

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Meltdown · Dec 06, 2013 at 02:03 AM

  1. 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.

  2. Load the prefab using the following code...

    GameObject gunPrefab = Resources.Load("yourgunPrefabName") as GameObject;

    if(gunPrefab != null) GameObject.Instantiate(gunPrefab, Vector3.zero, Quaternion.Identity);

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

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.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

23 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to instantiate a projectile only from the weapon prefab of the firing player? 1 Answer

Instantiate New Gun 1 Answer

Storing and using weapons and objects 0 Answers

Instantiate individual components of a prefab? 1 Answer

Issue Instantiating prefab in C# 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges