I like to lock a target based on Raycasthit, but it will change a ‘tag’ from the object AFTER a few seconds… if the RaycastHit exit, before 5 seconds, the ‘tag’ is not changed.
I have this code:
function Update () {
var foundHit : boolean = false;
var hit : RaycastHit;
var fwd = transform.TransformDirection (Vector3.forward);
foundHit = Physics.Raycast(transform.position, fwd, hit);
if (foundHit && hit.transform.tag != tagCheck) //&& !checkAllTags
foundHit = false;
if (foundHit)
{
// here is my problem. i need 5 seconds before execute....
yield WaitForSeconds (5);
// ...the next line
hit.collider.transform.tag = "lockEnemy";
print ("Mudeia a tag para = lockEnemy");
}
}
But, the line:
yield WaitForSeconds (5);
needs a coroutine to set properly… so how i can do this to work?
You have a few problems here. The major one is that you cannot yield inside of Update(). So you would need to create a coroutine to use yield. As an alternate you can use what I like to call a ‘timestamp’. I’m assuming what you want to happen is that the player needs to have an object in front of this game object continuously for 5 seconds in order to change the tag to ‘lockEnemy’. Here is some alternate code:
#pragma strict
var tagCheck = "Target";
var lockTime = 5.0;
private var locking = false;
private var timestamp = 0.0;
private var hit : RaycastHit;
function Update () {
if (Physics.Raycast(transform.position, transform.forward, hit) && (hit.transform.tag == tagCheck)) {
if (!locking) {
locking = true;
timestamp = Time.time + lockTime;
}
}
else {
locking = false;
}
if (locking && Time.time >= timestamp) {
hit.collider.transform.tag = "lockEnemy";
print ("Mudeia a tag para = lockEnemy");
}
}