I’m sure this has been discussed in other threads, but I don’t know what to search for and I found nothing. Now, if I had to do this only with one paticular object, everything would have been ok, but I want to check if different objects with a certain tag are close to the object that’s checking. Basicaly I want to detect objects. I can do this with 500 raycasts maybe, but I’m pretty sure this isn’t the right way to do it. Sorry for the bad explanation, but I wouldn’t have explained it better either on my own language
Put a rather large sphere object (with a collider) around the object and make it a trigger. Remove the renderer of course.
Then OnTriggerEnter() will tell you when something is close and OnTriggerExit() will tell you when something leaves.
Nice idea, but one problem comes to mind- if the object with the sphere is next to a wall, the sphere will clip through the wall and everything behind the wall, that touches the sphere will trigger the collider.
On such case do a ray cast between the player and the enemy, if it reaches the enemy no problem. Its a lot cheaper to do a ray cast in the odd situation than every frame.
Yes, but that’s my problem. How do I know to which enemy to do the raycast if they are 5 and only one is in range? Would I need something like a for-loop with all the enemies or something?
Have a list of current in range enemies which will be added OnTriggerEnter(). Then loop through those ones. You dont want to check every enemy just the ones close.
Thanks! And just a last question, which is pretty dumb, but how will I loop through the enemies in range. Sounds strange, but I haven’t looped between things, that change yet.
Assuming C#:
ArrayList m_enemiesInRange = new ArrayList(); // Init in start
foreach( GameObject in m_enemiesInRange )
{
// Ray cast to enemy, if hit process whatever.
}
I’m using JavaScript, so from what I understand it would be.
var enemies = new Array();
for(i=0, enemies.Lenght, i++)
{
raycast to enemies[i].GameObject
}
And when a new enemy is added I would add it like
enemies[enemies.Lenght + 1] = the enemy.
Right ?
Just a question than. How will I remove the enemies from the array ?
Arrays/lists/etc. don’t magically resize when you try to access out-of-range elements; you need to allocate space first. Using .Add with an Array does that for you, but trying to access array[ array.length ] will just throw a null exception.
var enemies : Array;
function AddEnemy( e ) {
enemies.Add( e );
}
function RemoveEnemy( e ) {
for ( var ix : int = 0; ix < enemies.length; ix++ ) {
if ( e == enemies[ix] ) {
enemies.RemoveAt(ix);
break;
}
}
}
Thanks for the help!