LoginSignup
0
0

More than 1 year has passed since last update.

【Unity】オブジェクトを初期位置・初期回転に戻す

Posted at

オブジェクトを初期位置・初期回転に戻す

少しうっかりしていてハマってしまったので戒めとして。
以下のようにTransformコンポーネントを取得しておくことでオブジェクトの位置・回転の初期化を実装しようとしていた。

private Transform _initialTransform;

void Start()
{
    // 初期位置の取得(のつもり)
    _initialTransform = gameObject.transform;
}

// 初期化関数
public void Reset()
{
    gameObject.transform.position = _initialTransform.position; // 位置の初期化(のつもり)
    gameObject.transform.rotation = _initialTransform.rotation; // 回転の初期化(のつもり)
}

これだとTransformコンポーネントを取得しておいたに過ぎないので、そのPositionやRotationの値は随時変化してしまう。
正しく初期化を行うには以下のようにPositionとRotationの初期値をそれぞれ別々に取得しておき、その値を使って初期化する。

private Vector3 _initialPosition; // 初期位置
private Quaternion _initialRotation; // 初期回転

void Start()
{
    // 初期位置・初期回転の取得
    _initialPosition = gameObject.transform.position; 
    _initialRotation = gameObject.transform.rotation; 
}

// 初期化関数
public void Reset()
{
    gameObject.transform.position = _initialPosition; // 位置の初期化
    gameObject.transform.rotation = _initialRotation; // 回転の初期化
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0