# How can this method to make a text mesh always face the camera be simplified? (Unity c#)

Despite a fairly heafty new years I am back trying to learn a bit more coding :D

This latest feature I am trying to add is a TextMesh that floats above a gameobject when the player is looking at it.

I does all work fine (except it kinda shakes a little but I'll look into that another time). But as I wrote the method to make the textMeshObject look at my camera, I just had a niggling feeling it could be written in less lines of code.

I actually get this a lot where I write several lines and think it must be able to be simplified, and after the code having several parts like this it can look pretty messed up.

Anyways, I thought i'd ask you experts on here if it was possible to do this an simpler (NOTE: I only want it to rotate on Y Axis):

  void FaceTextMeshToCamera(){
Vector3 origRot = textMeshObject.transform.eulerAngles;
textMeshObject.transform.LookAt(textLookTargetTransform);
Vector3 desiredRot = textMeshObject.transform.eulerAngles;
desiredRot.x = origRot.x;
desiredRot.z = origRot.z;
textMeshObject.transform.eulerAngles = desiredRot;
}


Eh, not really. You can save about two lines:

By moving the Y value over instead of both X and Z, we save a line:

void FaceTextMeshToCamera(){
Vector3 origRot = textMeshObject.transform.eulerAngles;
textMeshObject.transform.LookAt(textLookTargetTransform);
Vector3 desiredRot = textMeshObject.transform.eulerAngles;
origRot.y = desiredRot.y;
textMeshObject.transform.eulerAngles = origRot;
}


By seeing that we only need the one value we can save another (and avoid creating a local variable, although this saves virtually nothing in terms of RAM, as Vector3s are primitives and exist on the stack instead of the heap and don't need to be garbage collected):

void FaceTextMeshToCamera(){
Vector3 origRot = textMeshObject.transform.eulerAngles;
textMeshObject.transform.LookAt(textLookTargetTransform);
origRot.y = textMeshObject.transform.eulerAngles.y;
textMeshObject.transform.eulerAngles = origRot;
}

• thank you . that's exactly what i needed. And happy to know i was pretty much doing it right :) – Big T Larrity Jan 2 '18 at 2:18

using UnityEngine;
using System.Collections;

public Camera m_Camera;

void Update()
{
transform.LookAt(transform.position + m_Camera.transform.rotation * Vector3.forward,
m_Camera.transform.rotation * Vector3.up);
}
}

• You can simplify this to transform.rotation = m_Camera.rotation - ie. rather than constructing a new orientation that's identical to the camera's, just copy the camera's orientation wholesale. Note that both the code in your answer and the simplification above allow the object to rotate on any axis, not just the y, which the original question says is not as desired. – DMGregory Aug 8 '18 at 21:07