Hi. I started playing with Unity and C# few weeks ago, and I am going deeper and deeper everyday… ;). Today I want to write an algorithm, but I have encountered a problem with time that I can’t solve.
For sake of simplicity I have written points of what I want to achieve:
-
There is an ACTION that requires for example 3 seconds to complete.
-
If conditions are met (object is in ray, and space is pressed) - do ACTION (which takes 3 seconds)
-
whenever ACTION is interrupted(at least one condition is not present) - stop ACTION
-
whenever conditions are met again I want ACTION happen again and I want it to take again 3 seconds(do that action all over again)
I have almost done it, but the problem is:
I want to do something like timer:
every time conditions of action are met - "Set timer to 3 seconds and start that timer.
Update() - in this function check if action has completed successfully and also whenever conditions are not met “turn timer off”.
Thanks in advance.
UPDATE
I didn’t want to make it complex, but I think you are right, I should post my code. But I have changed few things since I posted it, maybe I mixed something. So, the idea is: Player controls a ship and he can ‘abduct’ objects. That’s the ‘Action’ I mentioned before.
using UnityEngine;
using System.Collections;
public class Abduction : MonoBehaviour
{
GameObject player;
Skills skills;
GameObject ship;
Transform shipTransform;
Abductable abductable;
bool isAbducting = false;
float timeToFinish;
void Start()
{
player = GameObject.Find ("Player");
skills = player.GetComponent<Skills>();
ship = GameObject.Find ("Ship");
shipTransform = ship.transform;
}
void Update()
{
if(Input.GetKey (KeyCode.Space))
{
Ray ray = new Ray(shipTransform.position, shipTransform.up*-1);
RaycastHit hit;
Debug.DrawRay (ray.origin, ((shipTransform.up*-1)*skills.AbductionRange), Color.green);
if (Physics.Raycast (ray, out hit, skills.AbductionRange))
{
if (hit.collider.CompareTag("Abductable"))
{
abductable = hit.collider.GetComponent<Abductable>();
SetTimeToFinish (abductable.Weight + skills.AbductionSpeed);
startAbduction(hit.collider, timeToFinish);
}
}
}
}
void startAbduction(Collider objectToAbduct, float timeToFinishAbduction)
{
isAbducting = true;
Debug.Log ("Abducting... Time to finish: " + timeToFinishAbduction + " Total time: " + Time.time);
Ray ray = new Ray (shipTransform.position, shipTransform.up*-1);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, skills.AbductionRange))
{
if (Time.time > timeToFinishAbduction)
{
Debug.Log ("Abduction FINISHED");
Destroy (objectToAbduct.gameObject); //destroy object
isAbducting = false;
}// else isAbducting = false;
}
}
void SetTimeToFinish(float finishTime)
{
if (!isAbducting)
{
timeToFinish = finishTime + Time.time;
} //else timeToFinish = 0f;
}
}