How to rotate the camera using code

In my project I have a Cube object. I want to make Camera follow it and I know, that I can do it just by dragging and dropping the Camera on the Cube in the Hierarchy. But I want to make it in the code. Here is the camera’s code:

    Transform cube;
	Transform _transform;

	void Start () {
		cube = GameObject.Find ("Cube").GetComponent<Transform>();
		_transform = GetComponent<Transform> ();
	void Update () {
		_transform.position = new Vector3(cube.position.x,
		                                  cube.position.y + 2,
		                                  cube.position.z - 2);

The problem is that Camera always looks to the one side, but Cube can rotate with buttons A/D and Camera should rotate with it.

transform.LookAt is handy for this sort of thing:


As an aside, I notice that you’re currently using a world-space offset from the cube. Perhaps you want that offset to be relative to the cube’s transform? We could do that using TransformPoint:

Vector3 offset = new Vector3(0f, 2f, -2f);
_transform.position = cube.TransformPoint(offset);

That way, we’re “behind” the cube no matter which direction it’s facing.