- Home /
Question by
garyreeddd · Dec 14, 2020 at 07:01 PM ·
c#scripting problemscripting beginnerbeginnerbeginners
How do I make a crouch script unity 3d
I just started learning to code in Unity and I wanted to create a crouch script by making the player's scale smaller, but it did not work; can you please help me understand what I've done wrong and fix my code and please make it as simple as possible?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
private bool JumpKeyWasPressed;
private GameObject plr;
private Vector3 scl;
// Start is called before the first frame update
void Start()
{
scl = gameObject.GetComponent("Player").transform.localScale;
plr = GameObject.Find("Player");
}
// Update is called once per frame
void Update()
{
// Jump
if (Input.GetKeyDown(KeyCode.Space))
{
JumpKeyWasPressed = true;
}
// Right and Left movement
float horizontalInput = Input.GetAxis("Horizontal");
GetComponent<Rigidbody>().velocity = new Vector3(horizontalInput * 2.5f, GetComponent<Rigidbody>().velocity.y, 0);
// Crouch
if (Input.GetKeyDown(KeyCode.C))
{
gameObject.GetComponent("Player").transform.localScale += new Vector3(0.5f, 0.25f, 0.5f);
}
else
{
gameObject.GetComponent("Player").transform.localScale += new Vector3(0.5f, 0.5f, 0.5f);
}
}
private void FixedUpdate()
{
// Jump
if (JumpKeyWasPressed == true)
{
GetComponent<Rigidbody>().AddForce(Vector3.up * 5, ForceMode.VelocityChange);
JumpKeyWasPressed = false;
}
}
}
Comment
In what way does it not work? Does it do nothing when you press C?
Answer by xxmariofer · Dec 15, 2020 at 12:38 PM
try this code
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
private bool JumpKeyWasPressed;
// Update is called once per frame
void Update()
{
// Jump
if (Input.GetKeyDown(KeyCode.Space))
{
JumpKeyWasPressed = true;
}
// Right and Left movement
float horizontalInput = Input.GetAxis("Horizontal");
GetComponent<Rigidbody>().velocity = new Vector3(horizontalInput * 2.5f, GetComponent<Rigidbody>().velocity.y, 0);
// Crouch
if (Input.GetKeyDown(KeyCode.C))
{
transform.localScale = new Vector3(0.5f, 0.25f, 0.5f);
}
else
{
transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
}
}
private void FixedUpdate()
{
// Jump
if (JumpKeyWasPressed == true)
{
GetComponent<Rigidbody>().AddForce(Vector3.up * 5, ForceMode.VelocityChange);
JumpKeyWasPressed = false;
}
}
}