Attach a camera to an object

Hello
How can I attach a Camera to an Object when I press a key ? I know it’s a simple question but please help me I’m new

There is a standard script “Smooth follow” Assets → Import package → scripts attach this script to camera, and choose your object as a target.

In case if you don’t need follow camera your object permanently, you can add and remove this script through the code (addComponent and probably Destroy methods)

This should work. I haven’t tested it though. This is assuming that when you say “attach”, you mean making the object you want to “attach” to a parent of the object the script is put on.

var attachTo : Transform;

function Update(){
    if(Input.GetKeyDown("space")){
        this.transform.parent = attachTo;
    }
}

Here’s an advanced version that supports changing the position and rotation to match that of the object you’re attaching to:

var attachTo : Transform;

var matchParentPosition : boolean = false;
var matchParentPositionOffset : Vector3;

var matchParentRotation : boolean = false;
var matchParentRotationOffset : Vector3;

function Update(){
    if(Input.GetKeyDown(KeyCode.Space)){
        this.transform.parent = attachTo;

        if(matchParentPosition){
	        this.transform.position = (attachTo.transform.position + matchParentPositionOffset);
	    }
	    if(matchParentRotation){ 
	        var newRotation : Vector3 = (new Vector3(attachTo.transform.rotation.x, attachTo.transform.rotation.y, attachTo.transform.rotation.z) + matchParentRotationOffset);
	        this.transform.rotation = Quaternion.Euler(newRotation.x, newRotation.y, newRotation.z);
	    }
    }
}

Again, both scripts are untested.

This does exactly what you asked:

var cameraIsAttached : boolean;

function Update () {

	if (Input.GetKeyDown(KeyCode.C)  cameraIsAttached == false){
	
		gameObject.AddComponent("Camera");
		cameraIsAttached = true;
	}

}

Thanks guys