- Home /
Must I always create a public variable for Prefabs?
Currently in a script called TestBehaviour.cs, I have a public variable called PicFrame
in the MonoBehaviour class. This class is attached to an empty GameObject in the scene. In my assets folder, I have designed a picture frame GameObject, which is composed of several other children GameObject with textures on them. I made that into a Prefab.
Within the Unity Editor, I dragged the picture frame Prefab to the PicFrame
variable to assign to it. And within the TestBehaviour.cs, every time before I want to use it, I will do an instantiate call on the Prefab assigned to PicFrame
variable.
This is how I have been working with assets in my game.
However, I am not sure if this is an efficient way of doing things. In a situation, I have several possible picture frame Prefabs that could be assigned to the PicFrame
variable. It depends on the game's current state that a particular picture frame prefab is used. I could declare 10 public variables, drag 10 prefabs to assign to each of the 10 public variables, and then decide within the code to use which of the 10 variables. When I want to add more frame Prefabs, I will add more public variables, and drag a new Prefab to it. Of course, I could make all of it into a List, but still I will still have to drag the Prefabs. Moreover, if I needed other types of Prefabs, I would have still have to declare new public variables for assignment.
Is what I have been doing the correct and ideal/best practice when working in Unity? If not, what is the best practice?
Answer by robertbu · Jan 09, 2013 at 10:19 PM
Rather than use 10 variables, consider use an array. You can set the size and then drag each Prefab to a different index.
public PicFrame[] arPicFrame;
If you wanted to automate, you could use scene game objecst rather than prefabs, tag the scene object, and the initialize the array with GameObject.FindGameObjectsWithTag().
Answer by dorpeleg · Jan 09, 2013 at 02:37 PM
I think the way you are doing it right now is good, but here is another possible solution:
Use Resources.Load
and with a bit of smart programming I think it's possible to make it load all prefebs in the Resources folder (even if you keep adding more) without changing the code.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Problem to play animation in C# 5 Answers
Game Object is Instantiating on same position 2 Answers
** why does my Enum parameter goes back to default value? ** 1 Answer