How to instantiate an object using both another object's location and vector3

Hi all, Is it possible to instantiate an object at another objects position and then use vector 3 to add a value to the Z axis of the instantiated object?

3 Answers

3

Umh, simply use the Instantiate() version where you can pass a position and rotation... http://unity3d.com/support/documentation/ScriptReference/Object.Instantiate.html

EDIT: As I realized now, you are trying to add an offset to the local Z of the object you instantiated, not the worldspace Z, as I assumed. The easiest way to do the former would be to use a "normal" Instantiate, and then add the offset afterwards in local space:

// this is .js UnityScript
newObject=Instantiate(sourceObject);
newObject.transform.localPosition+=Vector3(0,0,offset);

You can put anything you like in the Vector3 passed to Instantiate, in your case that would be "object.position+new Vector3(0,0,offset)". (omit the "new" if you use UnityScript instead of C#).

Yes. If you construct a new Vector3 with your Z offset you can add it to the position of the other object on instantiation. Like so... (I haven't actually tried this code, but it should all be there)

var targetObject : GameObject;
var newObject : GameObject;
var offset : float = 10;
var P : Vector3 = targetObject.transform.localPosition + Vector3(0,0,offset);

newObject = Instantiate(newObject, P, Quaternion.identity) as GameObject;

Seems something got mixed up in the last line there. Replace it with: newObject = Instantiate(targetObject, P, Quaternion.identity) as GameObject;

Note, that will add "offset" to worldspace Z, which is probably not what OoglyWoogly intended (and you tried to anwer), as I realized now. See my own answer, which I edited with a world space/local space disctinction.

Ok so i've got the following:

var roidPlusZ : Vector3 = roid.transform.localPosition + Vector3(0,0,50);

missileExplodeFire = Instantiate(missileExplodeFire, Vector3(roid, roidPlusZ, Quaternion.identity)as GameObject);

But im getting the following error: Assets/Scripts/Asteroids/AsteroidPhysics.js(40,77): BCE0024: The type 'UnityEngine.Vector3' does not have a visible constructor that matches the argument list '(UnityEngine.Rigidbody, UnityEngine.Vector3, UnityEngine.Quaternion)'.

any ideas?

roid is a rigidbody and missileExplodeFire is a particleEmitter

It would have been better to post this as a comment to Toxic Blobs answer, instead of an answer to your own question (which it is not). Anyway, see my comment to Toxic Blob's answer for an answer to your answer. Umh... :o)