Search code examples
c#rotationquaternions

A problem with the rotation of objects in c#


using System.Collections.Generic;
using UnityEngine;

public class RotationPlasmaCast : MonoBehaviour
{
    float LockPos = 0;
    public Transform Squid;
    float SquidRot = Squid.z;

    void FixedUpdate()
    {
        transform.rotation = Quaternion.Euler(LockPos, LockPos, SquidRot.rotation);
    }
}

I used this code to make the rotation of my projectile (PlasmaCast) the same as my player (Squid). Unity tells me:

A field initializer cannot reference the non-static field, method, or property 'RotationPlasmaCast.Squid

Does anyone know why Unity gives me an error?


Solution

  • Assuming you want to store the Squid's Z rotation for use elsewhere in your code, you would set your initial rotation to 0 and during your FixedUpdate() function you would update that value to match its current rotation and pass that into your transform like so:

    using System.Collections.Generic;
    using UnityEngine;
    
    public class RotationPlasmaCast : MonoBehaviour
    {
        float LockPos = 0;
        public Transform Squid;
        float SquidRot = 0;
    
        void FixedUpdate()
        {
            SquidRot = Squid.rotation.z;
            transform.rotation = Quaternion.Euler(LockPos, LockPos, SquidRot);
        }
    }
    

    Its worth noting that depending on the heirarchy of your GameObjects you may need to use 'localRotation' instead of 'rotation'