Enemy Ship Detection

Code below is my attempt at detecting an hostile ship at radar range but it is not working correctly at the moment. All the help I can get is welcome:smile:

var target : Transform;
var radarRange = 500.0;

function Update () {
	if(!target){
		if( (transform.Find( "UNSFDaedalus" ).position - transform.position).magnitude < radarRange ){
			target = transform.Find( "UNSFDaedalus" );
		}
   }else{
   DoSomthing();
   }
}

Also in the long run I am thinking of reading list of the enemy ships from another script(an array) any ideas welcome:smile:

Try sqrMagnitude instead of magnitude.

Also, as a recommendation, don’t do a Find on each Update. Save that to a variable in the Start method and access it directly.

Also, make sure the distance of 500.0 is ok for your scale.

You can make a Debug.Log to print the distance (sqrMagnitude) just to be sure of that.

sqrMagnitude is a good one thanks. However I need a method that can lock on to the spawning ships(which does not exist at Start()).

Try makeing one script a Master for the game have it contain all info you want and then when you need to get the list of units/ships in the game acsess it.

What I do is have the list of all units in game, when a unit is spawned it tells the list to add this unit. When a unit dies it removes itself from the master list.

Then when I want to see what units are nere this unit I do a “for loop” though the master list and get the distance for them and if they are nere this unit I add them to a target list that each unit carrys.

When spawning a unit I just put this in Start() on the unit.

	void Start () 
    {
        GameObject tempGameMasterGO = GameObject.FindGameObjectWithTag("GameMaster");
        gamemaster = (GameMaster)tempGameMasterGO.GetComponent(typeof(GameMaster));
        unitSelf = this;
        gamemaster.masterUnitList.Add(unitSelf);
	}

I store my units not by gameobject but by the script that has all the unit info. If i need to get the gameobject its as easy as: Unit.gameObject

You could try something like this. I’m at work so i can’t confirm that the code works or if it’s even typed correctly, but the jift of it’s in there somewhere.

var EnemyTag : String = "Enemy";
var EnemyList : GameObject[];
var Target : GameObject;
var distane : float;
var radardistance : float;

function Update(){

Player = transform.position;

EnemyList = GameObject.FindGameObjectWithTag(EnemyTag);

for(var Enemy : GameObject in EnemyList){
	distance = (Enemy.transform.position - Player).magnitude;
	}
	if(distance < radardistance){
		DoSomething(Enemy);
	}
}
function DoSomething(Enemy){

}
}