I’m new to scripting and am having trouble understanding what needs to be fixed with my code. When I test my script, it only allows me to use a+d to scale my object, but not q+s.
public class PlayerControl : MonoBehaviour
{
public Rigidbody rb;
void Update()
{
var s = rb.transform.localScale;
//squish
if (Input.GetKey("s") && Input.GetKey("q"))
{
rb.transform.localScale = new Vector3(0.5f, 3f, 1);
}
if (Input.GetKey("a") && Input.GetKey("d"))
{
rb.transform.localScale = new Vector3(3f, 0.5f, 1);
}
else
{
rb.transform.localScale = new Vector3(1, 1, 1);
}
}
}
else needs to go OUTSIDE of its corresponding if statement
You almost always want to use the && operator instead of the & operator. This can help performance because C# doesn’t even need to bother evaluating the right-hand side if the left-hand side is false.
Altogether:
if (Input.GetKey("s") && Input.GetKey("q")) {
rb.transform.localScale = new Vector3(3f, 0.5f, 1);
}
else {
rb.transform.localScale = new Vector3(1, 1, 1);
}
Thank you for the response! Unfortunately I caught the mistake just a second before you replied and ended up changing my script only to find a new problem. Sorry about that.
Because any changes you make in the first if statement (for q and s) will be overwritten by the if/else construct that comes after it. So no matter what happens with the first statement, either the if (Input.GetKey("a") && Input.GetKey("d")) section will run, or the else will run, and in either case, it will overwrite whatever happened earlier. You can fix this by putting all of your code into one if/else if/else construct, like this:
if (Input.GetKey("s") && Input.GetKey("q")) {
rb.transform.localScale = new Vector3(0.5f, 3f, 1);
}
else if (Input.GetKey("a") && Input.GetKey("d")) {
rb.transform.localScale = new Vector3(3f, 0.5f, 1);
}
else {
rb.transform.localScale = new Vector3(1, 1, 1);
}