C# Movement Script

I converted this small script from JavaScript to C# and I cant seem to get the Transform.TransformDirection working. I get this error

A field initializer cannot reference the nonstatic field, method, or property `UnityEngine.Transform.TransformDirection(UnityEngine.Vector3)’

I have tried different variations as well as instantiating it before creating the vector but no go.

using UnityEngine;
using System.Collections;

public class characterController3D1 : MonoBehaviour {
    
	public float speed = 6.0F;
    public float jumpSpeed = 8.0F;
    public float gravity = 20.0F;
	public float slopeLimit = 45.0f;
	
    public Vector3 vertical = Transform.TransformDirection(Vector3. forward);
    public Vector3 horizontal = Transform.TransformDirection(Vector3.right);
	
	
	public void movement() {
		
        CharacterController controller = GetComponent<CharacterController>();
		
		if(Input.GetAxis("Verticle") || Input.GetAxis("Horizontal")){
			controller.Move ((vertical * (walkSpeed * Input.GetAxis ("Vertical"))) * Time.deltaTime);
			controller.Move ((horizontal * (walkSpeed * Input.GetAxis ("Horizontal"))) * Time.deltaTime);
		}
		
    }

}

You have to move your variable definitions down in void Start(). like this:

...
public Vector3 vertical;

void Start()
{
   vertical = transform.TransformDirection(Vector3.forward);
}
...

public Vector3 vertical = Transform.TransformDirection(Vector3.forward);
public Vector3 horizontal = Transform.TransformDirection(Vector3.right);

Change the above to:

    public Vector3 vertical;
    public Vector3 horizontal;

then in Start() you can set them if you use a lower case t (which means the transform attached to this script)

vertical = transform.TransformDirection(Vector3. forward);
horizontal = transform.TransformDirection(Vector3.right);

This is because TransformDirection is not a static function but rather a member function. This means that you call it on a specific transfrom.

See the Unity Reference on this

In your case I am betting that if you change like this it will work.

public Vector3 vertical = transform.TransformDirection(Vector3. forward);
public Vector3 horizontal = transform.TransformDirection(Vector3.right);

all that has been done is change the Transform to transform, this changes for a class static function to the instance of the gameObject’s transform.