Having trouble making player run automatically

Please take a moment to look at this page for how to post code more nicely on the forums: Using code tags properly

(looks like this…)

using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float sspeed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector2 moveDirection = Vector2.zero;
void Start()
{
}
void Update()
{
   CharacterController player = GetComponent<CharacterController>();

   if (player.isGrounded)
   {
      // if player is on the ground, we normally don't want to move him vertically
      moveDirection.y = 0;
      // but if the jump button is pressed, then we do want him moving vertically

      if (Input.GetButton("Jump"))
      {
         moveDirection.y = jumpSpeed;
      }
   }
   else
   {
      // if player is not on the ground, then apply gravity to him
      moveDirection.y -= gravity * Time.deltaTime;
   }
   // constantly move horizontally
   moveDirection.x = speed;

   // finally, we actually apply the movement to the player
   player.Move(moveDirection * Time.deltaTime);
   }
}

Okay, if this is an exact copy/paste, do you have any compiler errors? It looks as though you’ve mispelled “speed” … and “sspeed” (<- declared).

I would suggest that you declare ‘player’ at the class level, and cache the GetComponent call (do it once) in Awake(). However, that’s just a bonus, and won’t actually be breaking your code at all.

Other than that, I’m not sure what is wrong, sorry.
Be sure to check the speed is not zero in the inspector?

1 Like