Hello everyone, i’m new to JavaScript and just wanted to show my simple shop system using the console and availability to add gold for testing purposes. It works well for me.
So what I want to ask is: is it in a good format? Anything I can do to make it simpler?
#pragma strict
var playerMoney : int = 10;
var hpPotion : int = 20;
function Update()
{
if(Input.GetKeyDown(KeyCode.G)) {
playerMoney += 2;
print("Player has earned 2 gold!");
}
if(Input.GetKeyDown(KeyCode.B)) {
if(playerMoney >= hpPotion){
playerMoney -= 20;
print("Player has bought Hp Potion");
}
else if(playerMoney < hpPotion)
print("Player doesn't have the sufficient funds!");
}
}
Hi, overall your code is okay but if your project gets bigger you will get some problems:
-comment(as usual), if you have 30 keyinputs your lost, just write //buy potion etc.
-no hard coding(e.g. playerMoney -= 20), make it a public variable. If you wanna balance the game later you dont want to change the 20 in 50 scripts/functions by hand(ah i see that u allready have a hpPotion but didnt use it ^^)
-dont put everything in Update(). Use more little function like
function Mousehandling() //everything that has to do with the mouseinput
function movementHandling() // wasd, arrow key etc.
function keyboardHandling() //
and call these function in Update() for a better overview
else if(playerMoney < hpPotion)
print("Player doesn't have the sufficient funds!");
This part is a big no-no. It works, but it can the cause of a lot of headaches, as the next line of your script would be executed regardless whether or not the if statement passed. You always want to have enclosing brackets, even if it is only one line.
No, it’s not because of JS, he’s just saying that it’s bad coding practice, because it can only lead to troubles. Enclosing it isn’t going to have a negative impact on performance, so learn to always take the time to do it, it will result in less mistakes/headaches in the future. You can even set Monodevelop’s settings to auto-create the enclosure when you type the first bracket, making it even easier. So you type the inward bracket, type your code, and it’s good to go.