- Home /
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);
}
}
}
Answer by ragnaros100 · Jan 23, 2013 at 04:32 PM
You have to move your variable definitions down in void Start(). like this:
...
public Vector3 vertical;
void Start()
{
vertical = transform.TransformDirection(Vector3.forward);
}
...
and this is because transform (and other behaviour properties) are undefined during the initialization process (all code outside functions) of an object.
Answer by CheeseGoat · Jan 23, 2013 at 04:53 PM
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);
Answer by vbbartlett · Jan 23, 2013 at 04:35 PM
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.
Your answer
Follow this Question
Related Questions
How to make camera position relative to a specific target. 1 Answer
Making a bubble level (not a game but work tool) 1 Answer
Player slows down when hitting an incline 0 Answers
Change character's Y rotation based on velocity. 1 Answer
[3D] Top-Down Make Character move in the direction of the position he is currently looking at? 1 Answer