I have a rotation script that is applied to two different objects. If I rotate one it also rotates the other and I do not want that.

Hello, I am making an AR application and I managed to get some of my objects to rotate by touch, however, when I touch one object, the other object rotates at the same time. I want them to act independently of one another, where rotating one doesn’t rotate the other.

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

public class rotation : MonoBehaviour
{
    private float turnSpeed = 100f;
    private float _startingPosition;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
            RaycastHit Hit;
            if (Physics.Raycast(ray, out Hit)) 
            {
                switch (touch.phase)
                {
                    case TouchPhase.Began:
                        _startingPosition = touch.position.x;
                        break;

                    case TouchPhase.Stationary:
                        if (_startingPosition > touch.position.x)
                        {
                                this.transform.Rotate(Vector3.forward, turnSpeed * Time.deltaTime);
                        }
                        else if (_startingPosition < touch.position.x)
                        {
                                this.transform.Rotate(Vector3.forward, -turnSpeed * Time.deltaTime);
                        }
                        break;
                    case TouchPhase.Ended:
                        Debug.Log("Touch Phase Ended.");
                        break;
                }
            } 
        }
            
    }
        
}

I think your ‘if’ is a little vague. Physics.Raycast returns true as long as it hits something. So your code makes the object rotate any time that the user touches something - even if that something is a different object.

Because both objects have the same code, both objects rotate any time that the user touches something - even if that something is a different object. So any time the user touches something, everything rotates.

You need to make the ‘if’ more specific. If the object that is touched is this object, then you rotate this object. Else, if some other object is hit, you do nothing.

Try revising your raycast and if like this:

RaycastHit HitInfo;
bool HitSomething;
HitSomething = Physics.Raycast(ray, out HitInfo))
if (HitSomething && HitInfo.collider.gameObject == this.gameObject)
    // Then do the rotation stuff

For the object that you dont want to rotate:

  • Add a rigidbody component in the inspector
  • lock the x, y, and z rotation, and also on the position

hopefully this helps