![](/img/trans.png)
[英]Changing the player's position in Update() or FixedUpdate() method?
[英]Rotating object in other function than Update/FixedUpdate
我只想知道每當我調用fixedupdate和update之外的函數時如何旋轉對象。 調用是從另一個函數進行的。 “ transform.rotation = e_rotation;” 在Update函數內部工作正常,但在外部沒有
public class PlayerControlls : MonoBehaviour
{
private Rigidbody ThisBody = null;
private static Quaternion e_rotation = new Quaternion(0, 0, 0, 0);
public Transform ThisTransform = null;
public static float m_ZAxis;
public static float m_WAxis;
void Awake()
{
ThisBody = GetComponent<Rigidbody>();
ThisTransform = GetComponent<Transform>();
}
public static void Rotation(float m_ZAxis, float m_WAxis)
{
e_rotation.z = m_ZAxis;
e_rotation.w = m_WAxis;
transform.rotation = e_rotation;
}
錯誤CS0120:非靜態字段,方法或屬性'Component.transform'需要對象引用
這不是更新/固定更新的問題,而是與static修飾符相關的問題,正如Adrita Sharma的評論所解釋的那樣。
您不能在靜態方法中訪問非靜態字段或任何非靜態類成員。
要解決您的問題,您只需從public static void Rotation
移除static修飾符。
如果您想繼續使用靜態功能(並在不獲取類引用的情況下在任何地方調用該方法),則可以使用單例模式。
這樣,您就有了一個靜態實例,但是您可以調用非靜態方法。
public class PlayerControlls : MonoBehaviour
{
public static PlayerControlls Instance;
private Rigidbody ThisBody = null;
private static Quaternion e_rotation = new Quaternion(0, 0, 0, 0);
public Transform ThisTransform = null;
public static float m_ZAxis;
public static float m_WAxis;
void Awake()
{
Instance = this;
ThisBody = GetComponent<Rigidbody>();
ThisTransform = GetComponent<Transform>();
}
public void Rotation(float m_ZAxis, float m_WAxis)
{
e_rotation.z = m_ZAxis;
e_rotation.w = m_WAxis;
transform.rotation = e_rotation;
}
}
然后,您可以使用PlayerControlls.Instance.Rotation
調用該方法。
有關單例的更多信息(如果需要): 統一使用單例的最佳方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.