I’ve been searching for a solution for this problem all day, but no luck. Basically what I have is a FirstPersonCharacter prefab (Unity Standard Assets), and a cube that has a box collider as a trigger. When the player enters the box, I want the height of the Character Component to decrease from 1.8 to 1. The goal is to make the character crouch when they enter an area. Here’s what my code looks like right now
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;
public class CrouchTrigger : MonoBehaviour {
public GameObject Player;
public GameObject trigger;
public bool crouched;
public CharacterController CC;
public Animation crouch;
void Start() {
CC = Player.GetComponent<CharacterController>();
crouch = Player.GetComponent<Animation>();
}
void Update() {
if (crouched == true) {
CC.height = 1;
}
}
void OnTriggerEnter() {
crouch.Play();
crouched = true;
}
}
I should note that the animation does play, but any attempts to adjust the CharacterController height does not work. I can make it work by setting the function to a key, but I want it to happen as the player passes through the sphere. Any help would be greatly appreciated, thanks!
I guess the sphere you mentioned is SphereCollider.
There are methods that can help you with interacting with colliders. It is always good to dont have too many things at Update().
Attach this script to GameObject with SphereCollider.
using UnityEngine;
public class sphere : MonoBehaviour
{
public GameObject Player;
public CharacterController CC;
public void Awake()
{
Player = GameObject.Find("Player");
CC = Player.GetComponent<CharacterController>();
}
public void OnTriggerEnter(Collider other)
{
CC.height = 1f;
}
}
Dont forget to mark “Is Trigger” at Inspector for Sphere Collider.
In addition you may need to tweak
CC.center.y
To change center of CharacterController, since height is offseted equally up and down from center of CC.
If sphere is as big as crouch area, you can add this to provided script to ensure that Character Controller will go back to 1.8f after leaving sphere.
public void OnTriggerExit(Collider other)
{
CC.height = 1.8f;
}
If you used “CC.center.y”, dont forget to implement the original value at OnTriggerExit.
NOTE: Any collider that will enter the sphere will trigger the effect, so it is just most simple solution for your problem and you may need to play with it to carve it to your needs, but it should give you an idea how to achieve this kind of behaviour.
If you would like this to trigger only if player character enters the sphere there is number of ways, but one of them can be.
public void OnTriggerEnter(Collider other)
{
if (other.gameObject.name == "Player")
{
CC.height = 1f;
}
}