Rotate a 3D Prefab around itself on any axis with a script

Hello! I need help to rotate a 3D prefab around its own axis (be it the x or y axis). Prefab consists of 10 child objects. Its purpose is to make the Prefab rotate 90 degrees by pressing the “A” button while only turning to the right. Unfortunately, the script does not work well, because all child objects actually rotate around their own y-axis and not around the central y-axis of the Prefab. I want the script to know the same as the Rotate Tool function for the y or x axes, only for pressing a specific button, all the while only turning to the right and 90 degrees. (By pressing the A button 4 times, the Prefab would rotate around its own Prefab axis. Here is the code:


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

public class RotatePrefab : MonoBehaviour
{
    // A prefab szülő objektuma
    public GameObject parentObject;

    void Update()
    {
        // Ha az A gombot lenyomják
        if (Input.GetKeyDown(KeyCode.A))
        {
            // Ellenőrzi, hogy van-e hozzárendelt szülő objektum
            if (parentObject != null)
            {
                // Minden gyerek objektumot 90 fokkal elforgat a Y tengely körül
                foreach (Transform child in parentObject.transform)
                {
                    child.Rotate(0f, 90f, 0f, Space.World); // Forgatás jobbra
                }
            }
            else
            {
                Debug.LogError("Nincs hozzárendelve szülő objektum!");
            }
        }
    }
}

Thanks!

Maybe you want to try the RotateAround method instead?

1 Like

Thank you Spiney199!

I will check it.