【UNITY】An object reference is required to access non-static memberが出た時の対処法

環境:
MacOSX10.11.4,Unity version5.4.03f Personal現象:
他のスクリプト内のstaticでないメソッドにアクセスしようとしたが、上記エラーが発生してビルドできない
対処方法:
エラーの意味合いとしては、staticでないメンバにアクセスするなら、きちんとインスタンス化したオブジェクトを参照してね、ということかと思います。ですので、参照先を正確に記述することで対処できました。
エラー例:
同一ゲームオブジェクトにtest1.csとtest2.csがあり、test1.csからtest2.csのmoveRight()を参照。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using UnityEngine; using System.Collections; public class test1 : MonoBehaviour { float speed = 1.0f; void changeSpeed(){ test2.moveRight (speed); } // Update is called once per frame void Update () { changeSpeed(); } } |
1 2 3 4 5 6 7 8 9 10 |
using UnityEngine; using System.Collections; public class test2 : MonoBehaviour { public void moveRight(float speed){ GetComponent<Rigidbody> ().AddForce (new Vector3(1,0,0) * speed); } } |
1 |
Assets/test1.cs(9,23): error CS0120: An object reference is required to access non-static member `test2.moveRight(float)' |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using UnityEngine; using System.Collections; public class test1 : MonoBehaviour { float speed = 1.0f; void changeSpeed(){ GetComponent<test2>().moveRight (speed); } // Update is called once per frame void Update () { changeSpeed(); } } |
1 thought on “【UNITY】An object reference is required to access non-static memberが出た時の対処法”