While writing code I noticed how this doesn’t work
if(Input.GetButtonDown("P2hp"))
{
var hpRayStall = Time.time + 1;
}
if(hpRayStall <= Time.time)
{
var hpRay = Physics.Raycast(lp.transform.position, transform.TransformDirection(Vector3.right), 2);
}
if(hpRay)
{
sceneManager.GetComponent(SceneManagerScript).p1HP -= 6;
}
However this did despite being the same thing, the only difference being where hpRayStall was created (I believe the proper term is declared)
var hpRayStall : float;
function Update()
if(Input.GetButtonDown("P2hp"))
{
hpRayStall = Time.time + 1;
}
if(hpRayStall <= Time.time)
{
var hpRay = Physics.Raycast(lp.transform.position, transform.TransformDirection(Vector3.right), 2);
}
if(hpRay)
{
sceneManager.GetComponent(SceneManagerScript).p1HP -= 6;
}
Your answer is here. Good luck.
It’s called scope; variables declared outside a function are global in scope. When you declare hpRayStall inside Update, it only exists in that function, and is destroyed when Update ends. So it’s declared again from scratch the next Update, instead of re-using the existing value. Note that if you’re declaring hpRayStall locally in Update, and the button isn’t down, then the default value (0.0) will be used. It would be more clear what was going on if you wrote it like this:
funtion Update () {
var hpRayStall = 0.0;
if(Input.GetButtonDown("P2hp"))
{
hpRayStall = Time.time + 1;
}