0

I just want to know how can I rotate objects whenever my function outside fixedupdate and update is called. Call is coming from another function to this rotation. " transform.rotation = e_rotation;" works just fine inside Update function, but no outside

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;
    }

error CS0120: An object reference is required for the non-static field, method, or property 'Component.transform'

Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
ilan1903
  • 3
  • 1
  • 3
    the problem is the `static` keyword. a static function belongs to the class, not its instances. either remove static or pass the transform you mean to rotate as argument. in general, avoid `static` when you have no real reason to use it. – yes Aug 08 '19 at 17:06

1 Answers1

0

This is not a matter of update / fixed update, but an issue related to the static modifier, as explained also by Adrita Sharma comment.

You cannot access non static fields or any non static class member in a static method.

To solve your issue, you can simply remove the static modifier from public static void Rotation.

If you want to keep using the static functionalities (and call the method anywhere without getting the reference to your class) you can use the singleton pattern.
In this way you have a static Instance, but you may call the non-static method.

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;
    }
}

Then you can call the method using PlayerControlls.Instance.Rotation.

Further info on Singletons if required: Best way to use Singletons in unity

Jack Mariani
  • 2,270
  • 1
  • 15
  • 30