I did search around first before I posted this question but couldn’t find anything.
So I made a prefab which basically contains a script to display a textfield.
What I wish to do is instantiate a clone of the textfield prefab and call a method on it, say to set the initial values.
So far I’ve been doing
GameObject textboxTransform = Instantiate (Resources.Load (“TextFieldPrefab”)) as GameObject;
TextboxScript textbox = textboxTransform.GetComponent();
My question is, Is the above the shortest/correct way of instantiating a prefab?
I had like to make the gui a bit more object oriented, where each textfieldprefab gameobject can represent one textfield.
What do you guys think? Thoughts?
the only time you should use resources.load is for dynamically created objects.
If you create a custom mesh mid game and store it and want to retrieve later.
If you want to have a prefab do
Public GameObject Prefab;
because you declared it public all you need to do is build/compile in monodevelop.
now go into unity editor and select the script. There will (because you made it public)
now be in the properties off to the right the script with a variable called Prefab (Empty)
Drag your actual prefab object over and drop it into that slot.
Unity recommends and prefers all prefabs be done that way (it has to do with later it makes it so you dont have filepath/name issues)
if you want a script on the prefab just drag and drop the script onto the prefab. Not the prefab in the scene but just the actual prefab in the file list. the list of stuff not perhaps in the scene but available.
later you can also use C# prefixes like
to make it so if a object with a script attached doesnt have something (like a rigid body or a collider) it automatically adds thats stuff too.
Like a shield would require a collider and you could just write a shield script and go if you dont have a collider add one.