Rotate an object to look at another object on one axis?

I have two gameobjects in a scene. My base object and a target object. I want the base object to rotate along it's Y axis to face or look at, the target object. How do I constrain the rotation of the base object to just the Y axis?

I have tried a slew of different ways to do this, with no luck.

targetPoint = targetObject.transform.position;

Quaternion targetRotation = Quaternion.LookRotation (targetPoint-transform.position ,Vector3.up);

transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 2.0);

I've also tried just using Transform.LookAt(targetPoint) with no luck either.

How can I constrain to just one axis (the Y-axis)? I don't care that the two objects are facing in the same direction, but what I'm trying to do is have the base object look at the target object with a fixed rotation axis. Thanks!

This is a 'frequently asked question' :) (It comes up quite frequently on the forums.)

There's more than one solution, but here's a common one (C#, untested):

var targetPosition = targetTransform.position;
targetPosition.y = transform.position.y;
transform.LookAt(targetPosition);

In C# this works assuming you have the object tagged as “Player” or change it to what yours is.

using UnityEngine;
using System.Collections;

public class GUIObject : MonoBehaviour 
{
	private GameObject target;
	private Vector3 targetPoint;
	private Quaternion targetRotation;

	void Start () 
	{
		target = GameObject.FindWithTag("Player");
	}

	void Update()
	{
		targetPoint = new Vector3(target.transform.position.x, transform.position.y, target.transform.position.z) - transform.position;
		targetRotation = Quaternion.LookRotation (-targetPoint, Vector3.up);
		transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 2.0f);
	}
}

I used this to rotate an NGUI label to always point at the player while only rotating in the Y. Attach it to what ever object you want to “look at” the player

http://forum.unity3d.com/threads/36377-transform.LookAt-or-Quaternion.LookRotation-on-1-axis-only

http://unity3d.com/support/documentation/ScriptReference/Transform.Rotate.html

function Rotate (xAngle : float, yAngle : float, zAngle : float, relativeTo : Space = Space.Self) : void

var y = //Whatever you want the y to be, being the targets y, just put this in the update function (Without the var).

function Update(){
    y = //Same thing here;
    transform.Rotate(0, y, 0, Space.World);
}

transform.LookAt (new Vector3(targetPoint.x, transform.position.y, targetPoint.z));