如何在GUI.Button中使用transform.position?能否用public Transform定义其位置?
Hey there! Let's tackle your two Unity GUI questions clearly and practically:
问题1:如何在GUI.Button中使用transform.position
First off, you need to understand a key point: GUI.Button uses screen pixel coordinates for its Rect position, but transform.position gives you world space coordinates (the position of an object in your 3D/2D scene). These are two totally different coordinate systems, so you can't plug transform.position directly into the Rect constructor—you'll get weird, off-screen positions most of the time.
To fix this, you need to convert the world space position to screen space using Camera.WorldToScreenPoint(). Also, keep in mind that Unity's screen coordinate system has its Y-axis starting at the bottom of the screen, while the old OnGUI() system uses a Y-axis starting at the top. So you'll need to flip the Y value to get the correct position.
Here's a quick example:
public Transform targetTransform; // Assign your object in the Inspector void OnGUI() { // Convert world position to screen position Vector3 screenPos = Camera.main.WorldToScreenPoint(targetTransform.position); // Flip the Y-axis to match GUI's coordinate system float guiY = Screen.height - screenPos.y; // Create the button with the converted position GUI.Button(new Rect(screenPos.x, guiY, 100, 100), "Test Button"); }
问题2:能否通过声明public Transform变量指定GUI.Button的位置
Absolutely! But as we covered in the first question, you can't directly use buttonPosition.position (world space) in the Rect—you need to convert it to screen space first. Also, note that in your example code, Public should be lowercase public (C# is case-sensitive!).
Here's the corrected version of your code with proper coordinate conversion:
public Transform buttonPosition; // Assign a transform in the Inspector void OnGUI() { if (buttonPosition == null) { // Add a safety check to avoid null reference errors GUI.Label(new Rect(10, 10, 300, 20), "Assign a Transform to buttonPosition in the Inspector!"); return; } // Convert world position to screen space Vector3 screenPos = Camera.main.WorldToScreenPoint(buttonPosition.position); // Adjust Y-axis for GUI's top-down coordinate system float adjustedY = Screen.height - screenPos.y; // Draw the button at the converted screen position GUI.Button(new Rect(screenPos.x, adjustedY, 100, 100), "Test"); }
A couple extra tips:
- If you're using a perspective camera, objects that are behind the camera will return negative screen coordinates—you might want to add a check for
screenPos.z > 0to only draw the button when the transform is in front of the camera. - The old
OnGUI()system is legacy now—if you're working on a newer Unity project, consider using the UI System (Canvas) instead, which is more flexible and handles position conversions more intuitively with elements likeButtonandRectTransform.
内容的提问来源于stack exchange,提问作者user9608906

