- Home /
How to reference a GameObject that shares position with gameObject
Hey there,
Well, thats a weird title. What i am trying to do is identify the object which position matches the gameObjects position that the script is attached to. Hell, that didn't make it better.
Here's my script:
public Vector2 tilePosition;
public float tileYPiece;
void Update()
{
tilePosition = transform.position;
tileYPiece = tilePosition.y + 0.5f;
pieceIdentifier();
}
void pieceIdentifier()
{
if ((tileYPiece) == GameObject.FindGameObjectWithTag("Piece").GetComponent<PieceScript>().piecePosition.y && tilePosition.x == GameObject.FindGameObjectWithTag("Piece").GetComponent<PieceScript>().piecePosition.x)
{
//the GameObject I need to reference does something
}
}
So the tile position is a Vector2(x, y), and the piece's position is a Vector2 (x, y) as well, and I need to reference the GameObject that shares position with the tile.
I'm confused as hell, if you hadn't noticed, and would reeally like some help
Thanks in advance
is the script on a different gameobject? thorn you must have one for each gameobject you want to reference, right? why not making it a child gameobject, then it's just it.
One of the first rules about dealing with floating point maths is that you should never directly compare the equality of two floats because, say, 1.0f + 1.0f is not necessarily exactly 2.0f. The fact that you are talking about "tiles" makes it sound like your objects can only occupy discrete positions that could be represented on a 2d grid - is that right?
You could retrieve the first gameobject which has it's transform's position the same as your piece ofcourse excluding your piece. Something like the following:
GameObject[] allObjects = UnityEngine.Object.FindObjectsOfType<GameObject>();
var obj = allObjects.FirstOrDefault(c => c.transform.position.x == Piece.X && c.transform.position.y == Piece.Y && c != Piece);
if (obj == null) throw new Exception("No object with same position found!");
Also note that comparing float's isn't going to always give you the wished for results.
Probably not your issue, but direct float equality comparisons are not always intuitive. It can often be helpful to compare their difference to some negligible value, rather than seeing if they values are "equal."
Your answer
Follow this Question
Related Questions
transform.find and Instantiate do not return the same type? 1 Answer
Loading a specific set of sprites with addressables 0 Answers
Duplicating Component with Some Scene References in Serialized Scriptable Object Class Reference 0 Answers
store a reference to a float in a variable? (similar to what the "ref" keyword does) 2 Answers
Drag and drop reference not working? 1 Answer