- Home /
Attaching camera to instantiated object
Hello everyone! I'm absolutely stumped. I spawn a player into the game along with a camera and a few blocks, but I can't fathom at all how to get that camera to follow the character once it's been spawned. I attempt to attach a camera to the spawn using the AddComponent method, which loads the camera into the scene absolutely fine. It's just the tracking I can't figure out. Any insight would be most appreciated!
var playerPrefab:transform;
var target:Transform;
var cam:Camera;
function Start() {
target = Instantiate (playerPrefab, transform.position, Quaternion.identity);
cam = gameObject.AddComponent(Camera);
}
function Update() {
// Presumably camera controls go in here such as lookat(target)?
}
Thanks very much!
The simplest $$anonymous$$ouseOrbit can be found in the standard assets- have a look at that. You're on the right track, but you should have a look at the way things work in the example projects as a guide to how you put your own stuff together.
Thanks for pointing me in the right direction, I'll get researching. Cheers!
Answer by Owen-Reynolds · Jan 25, 2012 at 03:28 PM
The code in most camera scripts has its own target variable, and is set to track that transform. All you have to do is take a pre-existing camera (you could create one in the code, but why bother?) and change that target var:
// your spawn line:
target = Instantiate(plyrPF, transform.position, Quaternion.identity) as Transform;
// tell camera to track it:
cam.GetComponenent<camScript>().target = target;
Your answer
Follow this Question
Related Questions
make player move in camera direction 1 Answer
Smoothly Move camera while looking at object 0 Answers
LookAt in opposite direction? 2 Answers
LookAt only when camera position changes 2 Answers