- Home /
How to instantiate prefabs with offset transform.position values?
I am making a game where different obstacle prefabs are randomly instantiated into the scene. They all have different sizes and are thus positioned on the Y axis to be placed right on the flat ground, so I just want to know how I would tell Unity to instantiate them with their transform.position offsets kept in mind (kind of like Quaternion.Euler). If anyone knows the transform.position equivalent of that, I would be very grateful. Thanks!
If you have installed it with the Unity editor, you can find the offline documentation here:
<path_to_unity_editor>\Editor\Data\Documentation\en\ScriptReference
Answer by Eno-Khaon · May 15, 2018 at 06:30 PM
Where transform.position
will give you the current position of a GameObject as a Vector3, transform.rotation
will give you the current rotation as a Quaternion.
To clarify, Quaternion.identity
is the definition for a baseline orientation. When the object has received no rotation, it still needs *something* to define its orientation. Unlike the Euler Angle representation of a rotation, you won't have a "zero" Quaternion.
@$$anonymous$$o-$$anonymous$$haon I just want to know how to instantiate a prefab of which the transform.position is not 0, 0, 0. Say I made a prefab and set its transform.position.y to be... say... 2.25. I then write Instantiate(Object, new Vector3(0, 2.25f, 0), Quaternion.identity);. But then, I set the prefab's Y position to be 1.63. How would I use I kind of Quaternion.Euler for transform.position to let the game know how high to spawn the object? Sorry if something like this wasn't apparent at first.
If you create a prefab with a position built into it and want to instantiate it at that position, you can easily use that:
// C#
public GameObject objectPrefab;
// ...
// Example using Start function
void Start()
{
// Use the prefab's position and rotation
Instantiate(objectPrefab, objectPrefab.position, objectPrefab.rotation);
// Override the prefab's coordinates (with zero-coordinates)
Instantiate(objectPrefab, Vector3.zero, Quaternion.identity);
// Provide an offset to the stored values
Instantiate(objectPrefab, objectPrefab.position + (Vector3.up * 1.63f), objectPrefab.rotation * Quaternion.AngleAxis(30.0f, Vector3.up));
}
Answer by Deathdefy · May 15, 2018 at 06:01 PM
Are you referring to a Vector3?
rotation is of type Quaternion and position is a Vector3. You could say the same thing for euler angles. If this isn't what you are referring to you'll have to add some more information to clarify exactly what you mean.
@Deathdefy I mean how would I instantiate a prefab with it's known offset position? Just like Quaternion.identity holds its known rotation... I think.
Yea this question completely changed after my comment lol.