LoginSignup
1
0

More than 1 year has passed since last update.

【Unity】スクリプトでlocalpositionを変更できない時の対処法

Last updated at Posted at 2022-11-13

はじめに

アニメーションがついてるときに、localPositionが移動できないエラーの解決法です。
調べても解決策がすぐにでなかったため、寄稿します。

環境

  • OS: Windows 11 Home
  • バージョン: 21H2
  • Unity Editer Version: 20203.27f1

やりたいこと

シーン内に置いているドット付き16分音符オブジェクトの名前変更、ポジション移動、スケール移動を以下のスクリプトで制御しようとしています。関数自体は、GameManager.csから動かしています。

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

using MusicXml;
using MusicXml.Domain;

public class TestClass: MonoBehaviour
{
    public GameObject _SixteenthNote; // 16分音符
    public void TestCreateScore (){
        GameObject NoteOrRest = GameObject.Find("eighth_note_dotted");
        NoteOrRest.name = "test_note";
        NoteOrRest.transform.localPosition = new Vector3(0.5f,0,0);
        NoteOrRest.transform.localScale = new Vector3(0.7f, 0.7f, 0.7f);
    }
}

オブジェクトは以下のアセットをアセットストアからとってきて使っています。

スクリプトからlocalpositionを変更できない

実行すると以下のGifのように、上に飛んで行ってしまいます。想定している挙動はx座標を0.5動かすだけなので、文字通りぶっ飛んだエラーです。

Animation.gif

よく見ると、名前とスケールの変更はできていますが、localPositionの値が変わっていません。

解決策

音符オブジェクトに付いているAnimaterコンポーネントの"Apply Root Motion"のチェック外し、Note Animator Controll(Script)コンポーネントを無効化して実行すると、上手く行きました。

Animation2.gif

どうやら、"Apply Root Motion"がOnだと、アニメーションによる位置の制御がスクリプトより優先されるらしくバグっていたようです。"Apply Root Motion"をOffにすればアニメーションによる位置移動は行われず、スクリプトから動かせるようになります。

また、Animator Controll(Script)コンポーネントはアセットに含まれていたものでキーボードでのアニメーションのコントロールなどを行っていたらしく、これとアニメーションが競合して、上に飛んで行っていた模様。詳しくスクリプトを読んでないので詳細は不明。重力をオフにしているのも原因かもしれません。

おわりに

簡単な動作ですが、1日ほど詰まりました。きつい。

参考

1
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
1
0