- Home /
Applying a Prefab to a Variable
Hi all, this is most probably an easy fix, but I have been looking for it for quite a while.
How do I assign a prefab to a variable without running it through the inspector?
For example I want to create a system that is like the following
var Weapon;
switch(Weapon){
case ("Large Stick"): Weapon = prefab("Large Stick"); break;
case ("Candycane"): Weapon = prefab("Candycane"); break;
case ("Lazer"): Weapon = prefab("Lazer"); break;
}
This is sorta the idea I'm looking for and i know the above script wont work, I am just asking how it is done.
Thanks Myhijim
Better question is: why? There is almost certainly a better way. String literals are always danger signals- if you have a solution that requires them, consider rethinking what you are doing.
I'm asking how to apply a prefab to a variable via its name, because I do not want hundreds of Transform variables in th inspector
Answer by Wolfram · Jun 16, 2012 at 02:07 PM
Well, you'll have to reference your objects somewhere - whether you type the 100 names in your script, or just drag the 100 prefabs into an array, it's not much of a difference, and the latter will give you much less hassle when dealing with your objects (although it will be more problematic if you later need to insert/delete objects from that array. Appending at the end is no problem)
One other method would be to put all your prefabs into a folder named "Resources". Then you can use Resources.Load("name") et al. to refer to these objects and instantiate them. However, note that the "Resources" folder will be included in all your builds, so the larger it gets, the larger your application will become, and unused objects in there will waste file size space of your application.
Exactly! Usually you can just declare a Transform or Gameobject array and assign your prefabs to them.
var prefabs : Transform[]; // assign your prefabs in the inspector.
// [...]
prefab[4] // the 5th prefab in the array
If you really want to handle it via a Resources folder and Resources.Load, your switch it totally useless if the switch statement is a string containing the exact asset name.
var weaponName : String;
var weaponPrefab : Transform;
// [...]
weaponPrefab = Resources.Load(weaponName);
Also you should use meaningful variable names and you should type them. dynamically types variables are slow and can give you strange errors at runtime since you and the compiler never know that's in the variable.
Your answer
![](https://koobas.hobune.stream/wayback/20220613072838im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How can I set a Transform Variable in a Prefab? 1 Answer
How can I modify a variable on an instance of a prefab after I created it? 2 Answers
How to delete a Variable in a script in game 1 Answer
Bullet Prefab spawning in multiple random positions and rarely the correct one (Unity 3D) 1 Answer
rot not working for 2nd prefab 2 Answers