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
}
}
}