- Home /
My Movement code does not work, help please.
I am trying to code C# for character movement. I have been following a tutorial, and this is the code that I ended up with.
{ void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
Rigidbody.Addforce(movement);
}
}
I do not know what my error is but when I try to test my game play, i get an error message in Unity saying "All complier errors must be fixed before you can enter play mode. please help me.
I am using the most recent version of Unity, unity 5
That is an incomplete script.
Aside from that you are using Rigidbody with a capital R when it should be lowercase, you need to make sure you have the namespaces and class declaration in there too.
Ok the Unity 5 docs state that you should use GetComponent(RigidBody) (uJS) or the C# equivalent.
http://unity3d.com/learn/tutorials/projects/roll-a-ball/moving-the-player
that is the tutorial from which I got the script. the script works for him. How do I make the script work for me? any suggestions?I honestly don't even know where to begin.
Answer by S_Darkwell · Mar 08, 2015 at 12:59 AM
The tutorial you are following was created using Unity 4. Unity 5 handles the accessing of certain components (such a Rigidbody) differently.
The easiest way to fix your code is to replace:
Rigidbody.AddForce(movement);
With:
GetComponent<Rigidbody>().AddForce(movement);
A better way would be to cache the Rigidbody component in Start(), then access the cached version thereafter. Here is tutorial's code rewritten for Unity 5 (and caching the Rigidbody component).
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float speed;
private Rigidbody Body;
void Start()
{
Body = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis( "Horizontal" );
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
Body.AddForce(movement * speed);
}
}
Hope this helps!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Physics.Raycasy not really using Layermask? 1 Answer