Unity:带标签的游戏​​对象,重置开始 location/position

Unity: Gameobjects with tag, Reset to start location/position

在移动、缩放、旋转后,我有大约 6 个带有标签(模型)的游戏对象 如何在单击按钮时将它们重置回起始位置。

我正在使用 Vuforia 和 Unity。

任何帮助将不胜感激,谢谢。

I have about 6 GameObjects with Tag (Model)

全部找出来存入数组

GameObject[] models = GameObject.FindGameObjectsWithTag("Model");

Move, Scale, Rotate how can I reset them back to start location when I click a button.

获取Start()函数中的position(Vector3)、scale(Vector3)和rotation(Quaternion),用for循环并将它们的值存储到临时变量中。单击 Button 时,调用将模型位置、比例和旋转设置为这些值的函数。

要在单击按钮时调用函数,您可以从编辑器或脚本中执行此操作。 ButtonInstance.onClick.AddListener(() => yourFunctionToCall());

I am a Unity newbie

这里没什么复杂的。

GameObject.FindGameObjectsWithTag

C# arrays.

GetComponent

Vector3

Quaternion

Unity Tutorials for beginners

Vector3[] defaultPos;
Vector3[] defaultScale;
Quaternion[] defaultRot;

Transform[] models;

//Attach Button from the Editor
public Button resetButton;

void Start()
{
    //Call to back up the Transform before moving, scaling or rotating the GameObject
    backUpTransform();
}

void backUpTransform()
{
    //Find GameObjects with Model tag
    GameObject[] tempModels = GameObject.FindGameObjectsWithTag("Model");

    //Create pos, scale and rot, Transform array size based on sixe of Objects found
    defaultPos = new Vector3[tempModels.Length];
    defaultScale = new Vector3[tempModels.Length];
    defaultRot = new Quaternion[tempModels.Length];

    models = new Transform[tempModels.Length];

    //Get original the pos, scale and rot of each Object on the transform
    for (int i = 0; i < tempModels.Length; i++)
    {
        models[i] = tempModels[i].GetComponent<Transform>();

        defaultPos[i] = models[i].position;
        defaultScale[i] = models[i].localScale;
        defaultRot[i] = models[i].rotation;
    }
}

//Called when Button is clicked
void resetTransform()
{
    //Restore the all the original pos, scale and rot  of each GameOBject
    for (int i = 0; i < models.Length; i++)
    {
        models[i].position = defaultPos[i];
        models[i].localScale = defaultScale[i];
        models[i].rotation = defaultRot[i];
    }
}


void OnEnable()
{
    //Register Button Events
    resetButton.onClick.AddListener(() => resetTransform());

}


void OnDisable()
{
    //Un-Register Button Events
    resetButton.onClick.RemoveAllListeners();
}

一种非常简单且几乎不需要编码的方法是制作游戏对象的预制件并重新实例化它们,在这种情况下预制件具有对象的初始状态,因此每个值都将被重置。 为了使它更容易,你可以制作一个父对象并制作一个预制件。

然后简单地:

Destroy(Parent);
Instantiate(Resources.Load("Prefabs/Parent"));