Is this code any good?
I recently starting working on a 2D turn based game like the first final fantasy. I created this script to create a random chance of battle when you are walking. It works, but I am still new to unity and programming and would like a second opinion on it and if you think there is a more optimal way to do it.
using UnityEngine;
using System.Collections;
public class BattleStart : MonoBehaviour {
public bool isWalking;
public double currentTime;
public float randomNumber;
double newNumber;
// Use this for initialization
void Start () {
newNumber = 1;
}
// Update is called once per frame
void Update () {
currentTime = Time.time;
//Creates a new random number between 1 and 100 every half second
if (currentTime > newNumber)
{
randomNumber = Random.Range (1,100);
newNumber = newNumber + 0.5;
}
// Determines if the player is walking
if ((Input.GetKey (KeyCode.W)) || (Input.GetKey (KeyCode.A)) || (Input.GetKey (KeyCode.S)) || (Input.GetKey (KeyCode.D)))
{
isWalking = true;
}
else
{
isWalking = false;
}
// When the player is walking, there is a chance of battle
if ((isWalking == true) & (randomNumber >= 90)) // 10% of a battle
{
Application.LoadLevel (1); //Loads the battle scene
}
}
}
Hello, I'm fairly new to program$$anonymous$$g myself, but your code looks good to me!
Answer by Filhanteraren · Nov 21, 2016 at 12:06 AM
Overall it looks good. A few things to consider;
Move your input check to a method that returns bool.
You dont need to generate and check random numbers when you are not Walking.
Use SceneManager instead. Application Load is the old method.
Here is my untested code:
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
public class BattleStart : MonoBehaviour
{
private float nextCheck = 1f;
private float interval = 0.5f;
private void Update()
{
if (IsWalking())
BattleStartCheck();
}
private void BattleStartCheck()
{
if (Time.time > nextCheck)
{
nextCheck = Time.time + interval;
if (Random.Range(1, 100) >= 90)
SceneManager.LoadScene(1, LoadSceneMode.Single);
}
}
private bool IsWalking()
{
if (Input.GetKey(KeyCode.W) ||
Input.GetKey(KeyCode.A) ||
Input.GetKey(KeyCode.S) ||
Input.GetKey(KeyCode.D)
)
return true;
return false;
}
}
Your answer

Follow this Question
Related Questions
Best way to spawn objects randomly on only x-axis on Mobile 0 Answers
One FBX with whole map from 3D soft or create map in unity ? 1 Answer
Unity 2D build for android, memory issue. Sprite import? 0 Answers
Is there a performance increase from using point textures instead of Bi/Trilinear textures? 0 Answers
WebGl RAM requirements 1 Answer