Hi,
I am working on a script that is supposed to find the closest object to a group of objects in the game … Of course with determining the type of these objects using another script … In any case it works well but it chooses the body that has the script as the closest object … which is Something logical … but I want to choose any of the available objects except the one that has the script
Important note: I also want to make the object carrying the script the same type of object that must be chosen the closest one in it
Well that’s pretty trivial. You just have to know the script instance on your own object. We don’t know where you attached your “objects1” instances (btw: terrible name. Please look up guidelines for class names in C#). I assume that the script is just attached to the same gameobject this script is attached to. In that case you can simply do:
inside your loop you can simply add this right at the beginning inside the loop:
if (currentObjects == myOwnObject)
continue;
This will skip the current object if it’s our own. If the script is not on the same object this script is attached to you have to use either GetComponentInChildren (if it’s on a nested object) or GetComponentInParent (if it’s on a parent object).
ps: You really need to work on your naming ^^. Don’t use the plural for variables which only holds a single object. Class names should always start with a capital letter and be descriptive what it represents. Since your component is attached to a gameobject and is only relevant for that one object it’s attached to using the plural makes no sense. You only use the plural in classnames if the class itself represents a collection. Even in this case it’s more common to use the suffix “Collection”.
Use meaningful names. “Object” is the most generic name possible. Choose a name that descibes what this class actually does or represents.
Finally the last line in your if statement inside your loop doesn’t make much sense. You actually move the object you try to find the closest object to around while iterating through the objects. So the result would make not much sense. That’s also another bad practise. You named your method “findTheNearestObject” but it doesn’t actually return anything and has unexpected sideeffects which the name does not suggest.