Unity Read Data From Prefab Without Instantiating It
Variables and the Inspector
Order of execution for event functions
Instantiating Prefabs at run time
PrefabsAn nugget type that allows you to store a GameObject complete with components and properties. The prefab acts as a template from which you tin create new object instances in the scene. More info
Run into in Glossary come in very handy when y'all want to instantiate complicated GameObjects The cardinal object in Unity scenes, which tin can represent characters, props, scenery, cameras, waypoints, and more. A GameObject's functionality is divers by the Components attached to information technology. More than info
Encounter in Glossary or collections of GameObjects at run time. Compared with creating GameObjects from scratch using code, instantiating Prefabs using code has many advantages considering you tin can:
-
Instantiate a Prefab using one line of lawmaking. Creating equivalent GameObjects from scratch requires many more lines of code.
-
Set, test, and alter the Prefab quickly and easily using the Scene A Scene contains the environments and menus of your game. Remember of each unique Scene file every bit a unique level. In each Scene, you lot place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary view, Bureaucracy and Inspector A Unity window that displays information virtually the currently selected GameObject, asset or project settings, assuasive you to inspect and edit the values. More info
Encounter in Glossary . -
Change which Prefab is instantiated without changing the code. You lot can make a simple rocket into a super-charged rocket, without any code changes.
Note: Y'all can download a Unity Projection containing all the examples on this folio, here:
InstantiatingPrefabsExamples.zip
Nuts of instantiating a Prefab
To instantiate a Prefab at run time, your code needs a reference to that Prefab. You lot tin make this reference by creating a public variable in your code to concur the Prefab reference. The public variable in your lawmaking appears as an assignable field in the Inspector. Y'all can so assign the actual Prefab yous want to utilize in the Inspector.
The script example beneath has a single public variable, "myPrefab", that is a reference to a Prefab. Information technology creates an instance of that Prefab in the Kickoff() method.
using UnityEngine; public class InstantiationExample : MonoBehaviour { // Reference to the Prefab. Drag a Prefab into this field in the Inspector. public GameObject myPrefab; // This script will simply instantiate the Prefab when the game starts. void Kickoff() { // Instantiate at position (0, 0, 0) and zero rotation. Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity); } }
To use this instance:
-
Create a new C# script in your Projection, and name it "InstantiationExample".
-
Copy and paste in the script example above into your new script, and salve it.
-
Create an empty GameObject using the menu GameObject > Create Empty.
-
Add the script to the new GameObject every bit a component by dragging it onto the empty GameObject.
-
Create whatever Prefab, and elevate it from the Project window A window that shows the contents of your
Avails
folder (Project tab) More info
See in Glossary into the My Prefab field in the script component.
When you showtime Play Mode, you should see your Prefab instantiate at position (0, 0, 0) in the Scene.
Yous can elevate a different Prefab into the My Prefab field in the Inspector to change which Prefab is instantiated, without having to change the script.
Because this first example is very simple, it may not seem to provide any advantage over just placing a Prefab into the Scene yourself. Even so, existence able to instantiate Prefabs using lawmaking provides you with powerful abilities to dynamically create complex configurations of GameObjects while your game or app is running, as shown in the following examples.
Common scenarios
To illustrate the strength of instantiating Prefabs at run time, hither are some basic situations where they are useful:
-
Building a structure out of a unmarried Prefab by replicating information technology multiple times in dissimilar positions, for example in a grid or circle formation.
-
Firing a projectile Prefab from a launcher. The projectile Prefab could be a complex configuration containing a Mesh The main graphics primitive of Unity. Meshes brand up a large part of your 3D worlds. Unity supports triangulated or Quadrangulated polygon meshes. Nurbs, Nurms, Subdiv surfaces must be converted to polygons. More info
See in Glossary , Rigidbody A component that allows a GameObject to be affected past simulated gravity and other forces. More info
Encounter in Glossary , Collider An invisible shape that is used to handle physical collisions for an object. A collider doesn't need to be exactly the same shape as the object'south mesh - a rough approximation is frequently more efficient and indistinguishable in gameplay. More info
See in Glossary , AudioSource, Dynamic Lite, and a child GameObject with its own trail Particle Organization A component that simulates fluid entities such as liquids, clouds and flames by generating and animating large numbers of minor 2nd images in the scene. More info
See in Glossary . -
A vehicle, building or character, for example a robot, breaking apart into many pieces. In this scenario, the case script deletes and replaces the complete, operational robot Prefab with a wrecked robot Prefab. This wrecked Prefab consists of separate broken parts of the robot, each gear up with Rigidbodies and Particle Systems of their ain. This technique allows you to accident up a robot into many pieces, with but 1 line of code, which replaces the original GameObject with a wrecked Prefab.
The post-obit sections show you how to implement these scenarios.
Edifice a structure
Y'all can use code to create many copies of a Prefab in a particular configuration well-nigh instantaneously. Using code to generate structures like this is chosen procedural generation. The instance beneath creates a wall of block instances.
To try this case, create the script beneath, name information technology Wall, and place information technology on an empty GameObject in your Scene.
using UnityEngine; public class Wall : MonoBehaviour { public GameObject cake; public int width = 10; public int tiptop = 4; void Commencement() { for (int y=0; y<height; ++y) { for (int x=0; ten<width; ++x) { Instantiate(cake, new Vector3(10,y,0), Quaternion.identity); } } } }
When you take done this, you should see the Cake variable in the Inspector, with the word None in the field. A value of "None" means that no Prefab has been assigned to this variable yet.
The example script above won't work until y'all assign a Prefab to the Block variable. To create a unproblematic block Prefab:
-
Cull GameObject > 3D Object > Cube.
-
Drag the cube from the Hierarchy window into the Assets folder in the Projection window. This creates a Prefab Asset.
-
Rename your Prefab to "Block".
-
Now that your Block Prefab exists every bit an Nugget, you can safely delete the cube from your Hierarchy.
Now that you have created a Block Prefab, you can assign it to the Block variable. Select your original GameObject (the 1 with the "Wall" script attached to it). And then drag the "Block" Prefab from the Projection window into the "Block" variable slot (where it says "None").
When you lot have finished this set-upwardly, click Play and you lot'll see that Unity builds the wall using the Prefab:
This is a flexible workflow pattern that you can use over and over again in Unity. Because you are using a Prefab in this script, you tin easily replace or edit the Prefab to modify the backdrop of the bricks in the wall, without needing to touch the script. You can also use your Wall script on other GameObjects in your Scene with dissimilar Prefabs assigned to them to have diverse walls made from different types of Prefab.
You tin use code to place a GameObject in a filigree, in circle pattern, randomly scattered, or whatever other configurations that you tin retrieve of to fit whatever game or app you are creating. Here'south another instance showing how to place instances in a circular germination:
using UnityEngine; public course CircleFormation : MonoBehaviour { // Instantiates prefabs in a circle germination public GameObject prefab; public int numberOfObjects = 20; public float radius = 5f; void Start() { for (int i = 0; i < numberOfObjects; i++) { float angle = i * Mathf.PI * 2 / numberOfObjects; float x = Mathf.Cos(angle) * radius; float z = Mathf.Sin(angle) * radius; Vector3 pos = transform.position + new Vector3(x, 0, z); float angleDegrees = -angle*Mathf.Rad2Deg; Quaternion rot = Quaternion.Euler(0, angleDegrees, 0); Instantiate(prefab, pos, rot); } } }
Instantiating projectiles & explosions
In this scenario:
-
A "Launcher" GameObject instantiates a projectile Prefab when the player presses the fire button. The Prefab contains a mesh, a Rigidbody, and a Collider, so information technology tin wing through the air and discover when a collision A standoff occurs when the physics engine detects that the colliders of two GameObjects make contact or overlap, when at to the lowest degree one has a Rigidbody component and is in motion. More info
See in Glossary occurs. -
The projectile collides with something and instantiates an explosion Prefab. The explosion Prefab contains a Particle System issue and a script that applies a force to surrounding GameObjects.
In the same way as the Block Prefab to a higher place, you can instantiate the projectile in merely one line of code, no matter how circuitous the projectile Prefab is. After instantiating the Prefab, you tin also alter any properties of the instantiated GameObject. For case, you can set the velocity of the projectile's Rigidbody.
Also as being easier to utilise, you lot can modify the Prefab later on on without touching the code. So if your projectile is a rocket, later on you lot could add a Particle System to information technology to make it get out a cloud trail. After y'all do this, all your instantiated rockets take particle trails.
This script shows how to launch a projectile using the Instantiate() part.
using UnityEngine; public form FireProjectile : MonoBehaviour { public Rigidbody projectile; public bladder speed = 4; void Update() { if (Input.GetButtonDown("Fire1")) { Rigidbody p = Instantiate(projectile, transform.position, transform.rotation); p.velocity = transform.forward * speed; } } }
In the code, the Prefab variable type is a Rigidbody, and not GameObject. This has two useful effects:
-
Only GameObjects that take a Rigidbody component tin be assigned to this variable. This is useful considering it helps make sure you're assigning the right GameObject to the variable.
-
The Instantiate method returns a reference to the Rigidbody component on the new instance. This is useful because it makes it unproblematic to gear up the velocity of the Rigidbody immediately after instantiating it.
When making a public Prefab variable, the variable blazon tin can be a GameObject, or information technology can be any valid Component type (either a built-in Unity component or one of your own MonoBehaviour script).
For GameObject blazon variables, you lot tin assign any GameObject to the variable, and the Instantiate function returns a reference to the new GameObject instance.
For component type variables (such as Rigidbody, Collider, and Light), y'all can simply assign GameObjects of that component type to the variable, and the Instantiate office returns a reference to that specific component on the new GameObject case.
The following script (placed on the projectile Prefab) performs the action of instantiating the explosion at the projectile'south current position and removing the projectile GameObject when the projectile collides with something.
using UnityEngine; public class Projectile : MonoBehaviour { public GameObject explosion; void OnCollisionEnter() { Instantiate(explosion,transform.position,transform.rotation); Destroy(gameObject); } }
Notice in the image above, which shows the scripts A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary running in Play fashion, the instantiated GameObjects appear in the Hierarchy, with the word "(Clone)" appended to the proper name.
Replacing a character with a ragdoll or wreck
Often in games, you might want to switch a character, vehicle, building or other Nugget from an "intact" state to a "destroyed" land. Rather than trying to modify the intact version of the GameObject (such equally removing scripts, adding Rigidbody components so on), information technology'due south often much more efficient and constructive to delete the entire intact GameObject and replace it with an instantiated destroyed Prefab. This gives you a lot of flexibility. Yous could use a different Material for the destroyed version, attach completely different scripts, or instantiate a Prefab containing the GameObject broken into many pieces to simulate a wrecked and shattered version of the original GameObject. Any of these options tin exist achieved with a single telephone call to Instantiate(), to bring your destroyed version into the Scene, while deleting the original.
Most chiefly, you can create the destroyed version which yous Instantiate() with completely dissimilar GameObjects compared to the original. For example, to create a breakable robot, you would model two versions: one that consists of a single GameObject with Mesh Renderer
and scripts for robot movement, and the other that consists of several skeletal parts that can be controlled individually by physics. Your game runs faster when using the model with simply one GameObject, because the model contains fewer triangles and so it renders faster than the robot that has many small parts. Also while your robot is happily walking around, at that place is no reason to accept it in separate parts.
To build a wrecked robot Prefab, you could:
-
Model your robot with lots of unlike skeletal parts in your favorite 3D modeling software, and export it into the Assets folder of your Unity Project.
-
Create an empty Scene in the Unity Editor.
-
Drag the model from the Project window into the empty Scene.
-
Add together Rigidbodies to all parts, by selecting all the parts and choosing Component > Physics > Rigidbody.
-
Add Colliders to all parts by selecting all the parts and choosing Component > Physics > Mesh Collider (enable the Convex option for faster performance).
-
Make sure you parent all the parts of your wrecked robot to a single root GameObject.
-
For an extra special effect, add a smoke-like Particle System as a kid GameObject to each of the parts.
-
At present you lot have a robot with multiple explodable parts. The parts can fall to the footing because they are controlled past physics, and each part creates a Particle trail due to the attached Particle Arrangement.
-
Click Play to preview how your model reacts, and make whatever necessary tweaks.
-
Drag the root GameObject into the Assets binder in the Project window to create a new Prefab.
The post-obit instance shows how you can model these steps in code.
using UnityEngine; public form WreckOnCollision : MonoBehaviour { public GameObject wreckedVersion; // Update is chosen once per frame void OnCollisionEnter() { Destroy(gameObject); Instantiate(wreckedVersion,transform.position,transform.rotation); } }
Yous can download a Project containing all these instance, hither: InstantiatingPrefabsExamples.cypher
Variables and the Inspector
Order of execution for event functions
Source: https://docs.unity3d.com/Manual/InstantiatingPrefabs.html
In Unity to spawn a prefab as a child of another object you just need to assign it to the desired parent object. Here's an example of how to do this, with a sample cube prefab:
ResponderExcluirhttps://codeprozone.com/code/csharp/28533/unity-instantiate-prefab-as-child.html