Get name of near object.

Hi everyone. I was wondering if there was a way to get the name of a near object (near being defined by a distance, e.g 2blender units. i am using a script which looks for any objects with the property vehicle in the range of 2 units. It then get’s the value of a string attribute name vehicle to determine which vehicle it is. any ideas?

Assuming ‘Near’ is the near sensor,

near = cont.sensors['Near']
if near.positive:
         nearobj = near.hitObject
         print (nearobj.name)

I suggest hitObjectList, because there can be more than one objects within the near sensor’s range.

Monster is correct, there can be more than one object in a near sensor’s range. So, the script would be:

near = cont.sensors['Near']
if near.positive:
    nearlist = near.hitObjectList
    for nearobj in nearlist:
        print (nearobj.name)

Monster, do you know if it is up and coming for other sensors to have lists (like the object’s rayCast function or the Collision sensor)?

I usually use a function as part of my AI to check for the nearest object with a specific property.
I can re-use this function many times in my AI with small adjustments.

Here is a stripped down version:

#### function
    
def get_closest(property):
    scn = GameLogic.getCurrentScene()
    
    obl = [ob for ob in scn.objects if ob.has_key(property) and ob != own]
    if obl != []:
        closest = [obl[0], own.getDistanceTo(obl[0])]
        for ob in obl[1:]:
            dis = own.getDistanceTo(ob)
            if  dis < closest[1]:
                closest = [ob,dis]
    else:
        closest = ["",0.0]

#### main part        
        
cont = GameLogic.getCurrentController()
own = cont.owner        
        
closest_vehicle = get_closest("vehicle")

closest_vehicle_ob = closest_vehicle[0]
closest_vehicle_dist = closest_vehicle[1]

You can also use this as part of your enemy AI to find the player, or for finding nearest doors, or even as part of a pathfinding script. It is very useful.

@Joeman16:

Near
Touch
Radar

as far as I know. I had a look as I was documenting the S2A library.

@smoking_mirror:
Your function is fine, but searches through all objects. If you have a lot of them, it might be better to search through the objects that are near (provided by the near sensor) only.

According to agoose77’s information, I would set the property of the near sensor to “vehicle”. This shrinks the resulting list even more.

I’ve had problems with getting objects from sensors and other methods before-
So I use more memory hungry functions, but only run them once or twice a second.

Sometimes, I use another function to get all the objects with a property on start up and store that as a game logic list.
But that only works if I don’t expect the list to change.