Unity中实现点击单个物体控制旋转启停的技术求助
Hey there! Let's sort out this issue where clicking anywhere stops/resumes all your rotating objects instead of just the specific one you click on.
What's Wrong With the Current Code?
Your current script listens for mouse clicks globally in Update()—every object with this script will trigger the rotation toggle as soon as you click anywhere on the screen, regardless of whether you clicked that specific object. That's why all objects react at the same time.
The Fix: Raycast to Detect Clicked Object
We need to check if the mouse click actually hits the object this script is attached to. We'll use Unity's raycasting system to do this:
using UnityEngine; public class EarthScript : MonoBehaviour { public bool rotateObject = true; public GameObject MyCenter; void Update() { // Check for left mouse click if (Input.GetMouseButtonDown(0)) { // Create a ray from the main camera through the mouse position Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out RaycastHit hit)) { // Only toggle rotation if the clicked object is THIS object if (hit.collider.gameObject == gameObject) { // Simplified rotation state toggle rotateObject = !rotateObject; } } } // Handle rotation logic as before if (rotateObject) { Vector3 axisofRotation = new Vector3(0, 1, 0); transform.RotateAround(MyCenter.transform.position, axisofRotation, 30 * Time.deltaTime); transform.Rotate(0, Time.deltaTime * 30, 0, Space.Self); } } }
Key Changes Explained:
- Raycast Detection: We cast a ray from the main camera through the mouse's screen position to identify which object was clicked.
- Targeted Toggle: We verify that the hit object is exactly the one this script is attached to (
hit.collider.gameObject == gameObject) before changing its rotation state. - Cleaner Toggle Logic: Replaced the verbose if-else block with
rotateObject = !rotateObject;to simplify state switching.
Important Note:
Make sure every object you want to interact with has a Collider component (like MeshCollider or SphereCollider) attached—raycasts can't detect objects without colliders! If using a MeshCollider, enable the "Convex" option if needed for reliable detection.
内容的提问来源于stack exchange,提问作者Fatma

