一旦将脚本应用于场景编辑器中的GameObject,我的函数就会运行。我只需要它在运行时影响对象

0 c# unity-game-engine

我有一个简单的脚本,该脚本应抓住GameObject的变换位置和旋转位置,然后在被Raycast击中时将其移回该位置。(当玩家撞到物体时,物体会四处移动)。

对于已经附加了脚本的对象,它的工作正常,但是当我将脚本应用于新的GameObject时,它将在场景编辑器中将变换的值重置为(0,0,0),(0,0,0)。

我敢肯定有一种更聪明的方法可以做到这一点。

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

public class TransformReset : MonoBehaviour
{
    private Transform LocalTransform;
    private Vector3 InitialPos;
    private Quaternion InitialRot;

    private Vector3 CurrentPos;
    private Quaternion CurrentRot;

    void Start()
    {
        InitialPos = transform.position;
        InitialRot = transform.rotation;       
    }

    public void Reset()
    {
        transform.position = InitialPos;
        transform.rotation = InitialRot;
        Debug.Log("resetting position of " + gameObject.name);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的光线投射脚本调用了“ public void Reset()”部分。但是我认为问题在于,它在获得有用的“ InitialPos”值之前先在场景编辑器中运行。

感谢任何帮助和建议。

Ruz*_*ihm 5

ResetMonoBehaviour引擎在特定条件下调用的消息。从文档中,重点是:

当用户在检查器的上下文菜单中单击“重置”按钮时,或在首次添加组件时,将调用“重置” 。仅在编辑器模式下调用此函数。重置最常用于在检查器中提供良好的默认值。

基本上,您对该方法的命名是与不应与之无关的内置行为发生冲突。如果将方法名称更改为其他名称,则应该可以正常工作:

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

public class TransformReset : MonoBehaviour
{
    private Transform LocalTransform;
    private Vector3 InitialPos;
    private Quaternion InitialRot;

    private Vector3 CurrentPos;
    private Quaternion CurrentRot;

    void Start()
    {
        InitialPos = transform.position;
        InitialRot = transform.rotation;       
    }

    public void ResetTransform()
    {
        transform.position = InitialPos;
        transform.rotation = InitialRot;
        Debug.Log("resetting position of " + gameObject.name);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在另一个类中:

transformResetComponent.ResetTransform();
Run Code Online (Sandbox Code Playgroud)