My problem is simply that the CharacterController.isGrounded function does not return anything. Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public Animator anim;
public CharacterController controller;
public float speed;
void Update()
{
if(controller.isGrounded) {
if(Input.GetAxis("Horizontal") > 0)
{
anim.SetInteger("condition", 1);
transform.Translate(speed - speed - speed, 0, 0);
}
if(Input.GetAxis("Horizontal") < 0)
{
anim.SetInteger("condition", 1);
transform.Translate(speed, 0, 0);
}
if(Input.GetAxis("Vertical") > 0)
{
anim.SetInteger("condition", 1);
transform.Translate(0, 0, speed - speed - speed);
}
if(Input.GetAxis("Vertical") < 0)
{
anim.SetInteger("condition", 1);
transform.Translate(0, 0, speed);
}
} else {
anim.SetInteger("condition", 2);
}
}
}
Here are my object components:
image?![Transform, Rigidbody (Use Gravity is on, Is Kinematic off), Box Collider (Is Not Trigger), CharacterController (Slope Limit: 0, Step Offset: 0, Skin Width: 0.08, Min Move Distance: 0.001) , Script(above)] (/Y:Kostya/Image.jpg
You don’t seem to have set the controller variable to reference the component. You’ll need the following in the Start() section:
controller = GetComponent<CharacterController>();
@KevRev, this is my updated code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public Animator anim;
public float speed;
CharacterController controller;
void Start() {
controller = GetComponent<CharacterController>();
Debug.Log(controller);
}
void Update()
{
if(controller.isGrounded) {
if(Input.GetAxis("Horizontal") > 0)
{
anim.SetInteger("condition", 1);
transform.Translate(speed - speed - speed, 0, 0);
}
if(Input.GetAxis("Horizontal") < 0)
{
anim.SetInteger("condition", 1);
transform.Translate(speed, 0, 0);
}
if(Input.GetAxis("Vertical") > 0)
{
anim.SetInteger("condition", 1);
transform.Translate(0, 0, speed - speed - speed);
}
if(Input.GetAxis("Vertical") < 0)
{
anim.SetInteger("condition", 1);
transform.Translate(0, 0, speed);
}
} else {
anim.SetInteger("condition", 2);
}
}
}
This is the output in the console:
slime (UnityEngine.CharacterController)
UnityEngine.Debug:Log(Object)
PlayerController:Start() (at Assets/Scripts/PlayerController.cs:14)
I think there is a conflict happening because you are using CharacterController, Rigidbody, and BoxCollider together. I suggest you remove the Rigidbody and the BoxCollider components and implement gravity by script, or remove the CharacterController and use Raycast to check if you are grounded.
I think it’s because you use Transform.Translate()
to move your player.
Try to use controller.Move()
instead, and let me know if it’s work.