- Home /
how to instantiate with an offset?
Hey guys, I'm trying to instantiate one object to the position of another but with an offset.
I've fudged around a bit;
if ( Input.GetMouseButtonDown (0) && lastHitObj )
{
if ( lastHitObj.tag == "placementPlane_Open" )
{
if ( structureIndex == 0 )
{
Instantiate ( allStructures[structureIndex], lastHitObj.structurePOS, Quaternion.identity );
structurePOS = Vector3 ( transform.position.x + .5, transform.position.y + .5, transform.position.z );
}
of course this is giving me errors :( I've done a search and previous questions answers must not be in javascript because they cough out errors.
if ( structureIndex == 0 )
{
Instantiate( allStructures[structureIndex], lastHitObj.Vector3(pos.x,pos.y+2,pos.z), Quaternion.identity );
}
Tried this as well, but that's also giving me errors.
Answer by JoaquinRD · Aug 17, 2013 at 06:19 PM
First of all, you mis-spelled "structurePOS" in the Instantiate call.
Also, try applying the offset like this:
var offset : Vector3 = new Vector3(0.5f, 0.5f, 0);
Instantiate(allStructures[structureIndex], lastHitObj.structurePOS + offset, Quaternion.identity );
thanks JoaquinRD, I noticed I did a type-o when I tried to retype the code out. (next time I'll just copy/paste) I'll give that a try!
Can I ask a quick question about your solution though? Being new to code, i don't understand why sometimes people put "f" beside the number. What does that do?
It converts the number to a float from a a double, two different types of numbers. Decimal numbers are doubles by default and the x, y, and z in Vector3 are floats, so the f is needed to make sure the number is the right type (float). I'm not sure if this is necessary in JavaScript since it might convert it automatically, but I know that it is necessary in C#. $$anonymous$$ake sense?
Yeah that makes sense, thanks for explaining that!
I did some adjustments to the answer you gave me as you created the var "offset" which replaces my old var "structurePOS".
code looks like this now;
if ( structureIndex == 0 )
{
var offset : Vector3 = new Vector3(0.5f, 0.5f, 0);
Instantiate(allStructures[structureIndex], lastHitObj.transform.position + offset, Quaternion.identity );
}
And works like a charm! Thanks for you help!
This instructs compiler about the exact type of the constant. F (or f) stands for 'float'. If you skip this, then in C# number like 0.5 is treated as double, and number like 5 as int. I believe in JavaScript, 0.5 is treated as float by default.
Ok so then to clarify, it's not needed in JavasScript? ( UnityScript )
Your answer
