- Home /
How to make it so enemies only move towards the player when the player is colliding with an object
It's more so when you touch an object with the tag "light" then any object with the tag "enemy" will become active and move towards the player.
#pragma strict
function Start ()
{
GetComponent("ENEMY").active = false;
}
function Update ()
{
}
function OnCollisionEnter (collision : Collision)
{
while(collision.gameObject.tag == "light")
{
GetComponent("ENEMY").active = true;
}
GetComponent("ENEMY").active = false;
}
[1]: https://www.dropbox.com/s/cc925rfeclh444a/Screenshot%202013-12-05%2008.26.30.png
[2]: https://www.dropbox.com/s/cc925rfeclh444a/Screenshot%202013-12-05%2008.26.30.png
Answer by stevethorne · Dec 05, 2013 at 03:16 PM
First, you don't want to use a 'while' statement there. That will loop forever if the object is a 'light' object. Replace that 'while' with 'if' and get rid of the line 'GetComponent("ENEMY").active = false;'.
Second, you will need to have an OnCollisionExit function that disables the Enemies if you're leaving the light object. It will be the same as your OnCollisionEnter function, but you will set the active state to false.
Like this? I forgot to mention I'm trying to make everything with the tag "enemy" active/inactive depending on the collision with "light".
function Start ()
{
GetComponent("ENE$$anonymous$$Y").active = false;
}
function Update ()
{
}
function OnCollisionEnter (collision : Collision)
{
if(collision.gameObject.tag == "light")
{
GetComponent("ENE$$anonymous$$Y").active = true;
}
}
function OnCollisionExit (collision : Collision)
{
if(collision.gameObject.tag == "light")
{
GetComponent("ENE$$anonymous$$Y").active = false;
}
}
@Jackie$$anonymous$$an That looks about right, try that out and see if it does what you need it to.
I put it on the Player but nothing happened, no errors at least.
Are the light objects you're colliding with marked as Trigger colliders? If so you'll need to use the functions OnTriggerEnter and OnTriggerExit.
I tried making the light objects triggers:
#pragma strict
function Start ()
{
GetComponent(gameObject.tag == "enemy").active = false;
}
function Update ()
{
}
function OnTriggerEnter (collision : Collision)
{
if(collision.gameObject.tag == "light")
{
GetComponent(gameObject.tag == "enemy").active = true;
}
}
function OnTriggerExit (collision : Collision)
{
if(collision.gameObject.tag == "light")
{
GetComponent(gameObject.tag == "enemy").active = false;
}
}
Nothing happens, the enemy still starts activated and doesn't deactivate