- Home /
Help in Javascript destroying Objects using character controllers and conditionals
Ok so I know I'm on the right track... I just know I need some help with some coding or someone to point me in the right direction. Here is the situation: Both players labeled as player 1 and player 2 are using character controllers to control them and when one is active the other is inactive (characters change when collecting a powerup). They are rigidbodies and the enemy is a rigidbody as well. When player one collides with the enemy (who has a trigger attached to him) I want player one to be destroyed and when player 2 collides with the enemy I want the enemy to be destroyed. Here is the code I'm working with... I know it's wrong but that's why I'm reaching out :)
private var enemy : GameObject;
private var player1: GameObject;
private var player2: GameObject;
function OnControllerColliderHit(hit: ControllerColliderHit){
enemy = GameObject.FindWithTag("enemy");
player1 = GameObject.FindWithTag("Player1");
player2 = GameObject.FindWithTag("Player2");
while (player1.active = true) {
if (hit.rigidbody){
Destroy (player1);
}
}
while (player2.active = true) {
if (hit.rigidbody) {
enemy.SetActiveRecursively(false);
} } }
I know the while (player1.active = true) is a boolean and this cannot work but I left it in there to show you what i'm trying to accomplish. I just don't know what to use at this point in the script. Thank you for any help or tips :)
While loops will work with booleans as well, but using while loops in this context is not to efficient why not just use a if(player.active)? ins$$anonymous$$d of a while loop?
Answer by FLASHDENMARK · Jan 26, 2012 at 08:52 PM
private var enemy : GameObject;
private var player1: GameObject;
private var player2: GameObject;
function OnControllerColliderHit(hit: ControllerColliderHit){
if(hit.rigidbody){
if(player1.active)
Destroy(player1);
if(player2.active)
enemy.SetActiveRecursively(false);
}
}
There is no reason to use a while loop(use simple if statements instead), or check the same condition twice with only different "sub-conditions".
I thought that gameObject.active is a boolean? Therefore it is only used to declare true or false. e.g. player1.active = true;
I declare whether player 1 is true or false in the powerup script however the code you suggested for this script stops the game whenever either character collides with the enemy. Thank you for the tips to get rid of the "while" statement... one more step in the right direction! However if you have any more ideas to get this working I'm very grateful. Thanks!