- Home /
aim 3D text at camera
I am trying to aim instantiated 3d Text at the camera. It all compiles but the text won't aim. Here's the code:
Instantiate(textMesh, pos, textMesh.transform.rotation );
GameObject cam = GameObject.FindWithTag("MainCamera");
Debug.Log (cam);
target = cam.transform;
Transform textTransform = textMesh.transform ;
Debug.Log (textTransform);
textTransform.LookAt(target);
Thanks for any solutions.
Answer by HarshadK · Dec 06, 2016 at 05:20 AM
You need to set the LookAt for the instantiated object. You are doing it for the textMesh currently. It should be:
GameObject instantiatedTextMesh = (GameObject) Instantiate(textMesh, pos, textMesh.transform.rotation );
GameObject cam = GameObject.FindWithTag("MainCamera");
Debug.Log (cam);
target = cam.transform;
Transform textTransform = instantiatedTextMesh.transform ;
Debug.Log (textTransform);
textTransform.LookAt(target);
it wouldn't take the GameObject casting because, the Text$$anonymous$$esh is not a GameObject. So I instantiated it as a Text$$anonymous$$esh and then it all worked. Wooot !
Text$$anonymous$$esh instantiatedText$$anonymous$$esh = (Text$$anonymous$$esh) Instantiate(text$$anonymous$$esh, pos, text$$anonymous$$esh.transform.rotation );
GameObject cam = GameObject.FindWithTag("$$anonymous$$ainCamera");
target = cam.transform;
Transform textTransform = instantiatedText$$anonymous$$esh.transform;
textTransform.LookAt(target);
thanks Harshad. This is a step forward. The text$$anonymous$$esh now instantiates facing the camera, but then the game freezes and gives this message "InvalidCastException: Cannot cast from source type to destination type." So I guess it doesn't like me telling the text$$anonymous$$esh that it is a GameObect.
On which line is it exactly throwing that exception?
the error occurs on GameObject instantiatedText$$anonymous$$esh = (GameObject) Instantiate(text$$anonymous$$esh, pos, text$$anonymous$$esh.transform.rotation );
changing GameObject to Text$$anonymous$$esh works. for whatever reason unity can't recast 3d text as a GameObject.