0
\$\begingroup\$

I have a camera with y rotation of 0.

And i have a canvas with position value of (0f,76.29f,41.82f). The size value of the canvas is (194.1f,307.8f). I want to modify the z value of the canvas to -10.

public Canvas textcanvas;
void Start () {
textcanvas.anchoredPosition = new Vector3 (0f, 24.5f, -10f);
}

But i get an error "error CS1061: Type UnityEngine.Canvas' does not contain a definition foranchoredPosition' and no extension method anchoredPosition' of typeUnityEngine.Canvas' could be found. Are you missing an assembly reference?"

Also, when i succeed moving the canvas, does the size of it adapting to the camera automatically?

\$\endgroup\$
  • \$\begingroup\$ ((RectTransform)textcanvas.transform).anchoredPosition \$\endgroup\$ – Draco18s no longer trusts SE Nov 30 '17 at 2:24
  • 2
    \$\begingroup\$ @Draco18s: a one-liner answer is still worth sharing as an answer. ;) (Of course, adding a second line explaining why you can't access it from the canvas reference alone would be even better) \$\endgroup\$ – DMGregory Nov 30 '17 at 2:49
1
\$\begingroup\$

((RectTransform)textcanvas.transform).anchoredPosition

The problem here is a very basic one: Canvas objects aren't Transforms. Transform objects are the only ones that contain position information, so you can't modify the position of the canvas by calling textcanvas.anchoredPosition because it doesn't exist there, you need to access the canvas's Transform: textcanvas.transform.anchoredPosition

However this won't work either, not directly, because there are two Transform classes:

  • Transform (for most GameObjects)
  • RectTransform (for most UI objects) which extends Transform

So we have to cast from one to the other, as the GameObject.Transform property is of type Transform, not RectTransform and anchoredPosition is a property of RectTransform and not Transform. Hence the final solution:

((RectTransform)textcanvas.transform).anchoredPosition

|improve this answer|||||
\$\endgroup\$
1
\$\begingroup\$

If you want the canvas to appear in front of a camera, you need to change the Canvas component to "Render Mode: Screen Space (Camera)" or "World Space" and then drag your camera into the canvas component.

If you want your menu to appear "transformed" I find the easiest thing to do is make an empty object under your canvas (I called it MenuTransform), and then place all your UI elements as children of that (like the panel in this example). Then, you can transform all the elements at once.

unity

|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.