Instantiate based on camera axes

Hello, everyone.

I’m working on a project in Unity that requires the creation of several objects in line with the camera’s position at any given moment - that is to say, the camera is free to rotate around the scene, but I need to instantiate a formation of objects based on the direction it’s pointing at any moment. These objects then move in several different directions.

I got the camera to work like I need it in the first place by making it a child of a “Camera Field” object and making that rotate instead of moving the camera around and trying to force it to stay locked on to a specific point (it’s an orbital camera).

However, now I’m using the following code to instantiate the Rigidbodys I need:

var dot1 = Instantiate(oneOfTheFinickyObjects, playerCam.localPosition + Vector3(0,0,19.5), transform.rotation);

then I set their velocities and send them on their way.

I didn’t anticipate that, because the camera is a child object, playerCam.localPosition never changes. Since these objects are spawned in world space, they are always relative to the world axes and thus they don’t go where I need them (so that their formation faces the camera).

I looked at this thread:
http://forum.unity3d.com/threads/30654-SOLVED-Instantiate-as-child
but, if I combine the solution there with my above code, I just have a bunch of child objects that are still in the wrong places, because they’re still being instantiated in world space.

TL;DR version: I need to tell some objects to spawn N units in front of the camera along the camera’s own Z-axis without taking the camera out of its parent object. Please tell me, is there a way to do this?

Sincerely,
JA

ScreenToWorldPoint fed with the center of the screen.

I’m not sure that’s the optimal solution here. It sounds like the OP just wants to spawn some objects at positions relative to a particular transform, in which case Transform.TransformPoint() or Transform.forward would probably be more suitable. E.g. (untested):

spawnPosition = transform.TransformPoint(new Vector3(0f, 0f, 10f));
// Or...
spawnPosition = transform.position + transform.forward * 10f;

Alright, long story after this.

First off, Jesse, thanks for your help. I hadn’t thought of using the vectors directly (HERP DERP).

I realized that the question I originally asked wasn’t generalizable and thus I had a problem if I tried spawning the particles anywhere other than directly in front. Then I did the obvious: I put up target objects and set their rotation to that of the camera, then instantiated using (yes!) the directional vectors of the target.

Works great now.