2
votes

I need help with my project in unity

I want to stop each object by clicking on it.

What I did so far:
all my objects rotate but when I click anywhere they all stop, I need them to stop only if I click on each one.

This is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EarthScript : MonoBehaviour
{
    public bool rotateObject = true;

    public GameObject MyCenter;
    // Start is called before the first frame update
    void Start()
    {   
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {

            if(rotateObject == true)
            {
                rotateObject = false;
            }
            else
            {
                rotateObject = true;
            }
        }
        if(rotateObject == true)
        {
             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);
        }
    }
}
1

1 Answers

2
votes

Theres two good ways to achieve this. Both ways require you to have a collider attatched to your object.

One is to raycast from the camera, through the cursor, into the scene, to check which object is currently under the cursor.

The second way is using unity's EventSystem. You will need to attach a PhysicsRaycaster on your camera, but then you get callbacks from the event system which simplifies detection (it is handled by Unity so there is less to write)

using UnityEngine;
using UnityEngine.EventSystems;


public class myClass: MonoBehaviour, IPointerClickHandler
{
   public GameObject MyCenter;
   public void OnPointerClick (PointerEventData e)
   {
    rotateObject=!rotateObject;
   }


   void Update()
   {

    if(rotateObject == true)
    {
         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);
    }
}