- Home /
For loop not working
I got a little bit further with scripting and decided to make a small rpg, now im trying to just set up a script to cast Fire ball. i'm making a fault somewhere, just can't quite seem to find where.
using UnityEngine;
using System.Collections;
public class Fireball : MonoBehaviour {
public int manaCost = 30;
private string spellName = "Fire Ball";
public float castTime = 35.5f;
private float curCastTime = 0f;
private bool spellCasting = false;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if(Input.GetKeyDown(KeyCode.G))
{
for(float i = 0; i < castTime; i += Time.deltaTime)
{
Debug.Log("---Working---");
GUI.Box(new Rect(Screen.width / 2 - 50, Screen.height * 0.9f, castTime / curCastTime, 50), curCastTime + "/" + castTime);
i += Time.deltaTime;
}
}
}
void OnGUI()
{
}
}
Btw, this is just to make the loading barr work, you know, for charging spells, i know the GUI.box is in the wrong place, but it doesn't even show my Debug.Log, so im trying to figure out why it's not going through the loop
Answer by aldonaletto · Nov 19, 2011 at 08:50 PM
I've not found the reason why Debug.Log isn't printing anything, but the whole thing is wrong: you can't block Unity with a lengthy for like this (not to mention the GUI.Box inside Update) - nothing will happen while this for is counting time. You could something like this instead:
float timeBox = 0;
void Update () { if(Input.GetKeyDown(KeyCode.G)) // if g pressed... { timeBox = castTime; // start the timer } if (timeBox >= 0) // decrement timer while its >= 0 { timeBox -= Time.deltaTime; } }
void OnGUI() { if (timeBox > 0) // display the box while timeBox > 0 { GUI.Box(new Rect(Screen.width / 2 - 50, Screen.height * 0.9f, castTime / curCastTime, 50), curCastTime + "/" + castTime); } }
Thank you a lot, i made the mistake of not attaching it to an object, so the script wouldn't be excecuted. and its true, when i did attach it, my game just crashed for a few seconds and than the bar was suddenly there, i thank you a lot for this script, i can continue now
How excactly do i do that :S, im sorry im fairly new here
Click the "check" button below the voting thumbs in the answer. It's important to accept the answer: it helps other people to find solution for similar problems.
Your answer
Follow this Question
Related Questions
C# for loop with 2 ints 2 Answers
For loop C#? 2 Answers
Using for as while. 3 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers