- Home /
Getting instance ID from position
Hello people! I'd like to start off by saying, yes, I am new to Unity, but I do have some game creating experience.
So, to the point. I'm trying to figure out how I can fetch the ID of an instance if all I know about it is it's position. I'm using this to destroy blocks (not a Minecraft clone.) Basically, I'm looking for something that will return the ID of an object at whatever location I chose.
Not really sure where to start on this honestly. Oh! One more bit of information that may or may not be helpful. All of these block instances where created using Instantiate. I created a prefab and placed them in the room in game using Instantiate.
Also, I'm trying to stick to Javascript for the time being. Learning two new languages at once would be a bit of a headache, but if C# is the way to go on this, then so be it. :)
I believe that is all of the information that I have to offer at this moment.
Answer by syclamoth · Feb 11, 2012 at 06:59 AM
Short answer: no, you can't get an object reference just from position data alone, without creating a complex object indexing system (look up octrees, it's where I'd start on this one).
However, for what you are doing here, there's probably a simpler way. If the objects you are trying to find have colliders, you can use Physics.Raycast or Physics.Linecast to get information about colliders detected in a line. If you know two points that the object is definitely between, you can use one of these functions to give you a reference to the first object found that intersects that line.
If your blocks are arranged in a grid, you can also use a more straightforward kind of indexing system. If you create a finite grid, with a 'size' in each dimension and a scale, you can transform world-coordinates to grid-coordinates fairly simply, and then if your blocks are stored in a 2d (or 3d) array that corresponds to the grid, you can access them like that (by transforming world coordinates to grid coordinates, and then indexing the array based on the grid coordinates).
If your objects are guaranteed to remain in one spot, you could also use a dictionary, that maps between Vector3 positions, and Transform objects. That way, you can find the object that is exactly in the point that you specified. I wouldn't recommend this, however, because Vector3s may not be precise enough to perfectly map in the way that you would need for this. (Also, I'm not especially clear on how to use .net generics in UnityScript- I'm told it's possible, but I've never done it.)
Your answer
Follow this Question
Related Questions
when testing in the game mode , shots don't fire ? 1 Answer
I need help with the location of instatiated objects on the scene and correct interaction with this 2 Answers
Instance child global position 1 Answer
How to set the mouse x and/or z position as a variable 1 Answer
How do I get the global position 2 Answers