- Home /
If statment based on a function not working
I'm working in a AI script, and i have made the following function to check if the enemy can see the player.
function CanSeePlayer(){
var hit : RaycastHit;
var rayDirection = playerObject.transform.position - transform.position;
if (Physics.Raycast (Seeker.transform.position, rayDirection, hit)) {
if (hit.transform.tag == "Player") {
Debug.Log("Can see player");
return true;
}else{
Debug.Log("Can not see player");
return false;
}
}
}
If i put this code outside of the function and in the script it self, it works fine.
But when i try to access the function like this:
if(!CanSeePlayer){
Debug.Log("I cant see the player")
}
The script dosent work, and the Debug command dosent get run, even though it should.
Answer by Silverfell-2 · Apr 21, 2010 at 03:37 PM
Should it not be:
function CanSeePlayer():boolean { }
hehe - nice JS-Fu :) for some reason I'm re$$anonymous$$ded of: http://thedailywtf.com/Articles/Classic_WTF_-_What_is_Truth_0x3f_.aspx
Answer by duck · Apr 21, 2010 at 02:34 PM
Well I was initially going to say that tou need to access the function like this:
if (!CanSeePlayer()) {
(notice the brackets after the function name), however after testing it, in a quirk of javascript syntax, it seems you don't actually need the () so that's not the answer.
Do none of the debug commands run? (you have 3). Do you get any errors?
Another thing I noticed is that you're building the ray direction as the vector between this object and the player object, however you're then casting it from the "Seeker" position (rather than this object's position). Perhaps you meant to write:
if (Physics.Raycast (transform.position, rayDirection, hit)) {
Since you haven't specified what "Seeker" is, it's difficult to know if that part of the code is correct.
No, none of my 3 Debug commands gets run.
The seeker is the part of the enemy object and it dosent change anything when i change it to what you posted.