Public GameObject set to any instance with a tag
Hi, I am working on a small puzzle game that requires a player to drag and drop sprites from a bank of sprites, to build a path.
.
.
To do so I am following a simple drag and drop puzzle game tutorial. However with this guide they are using 5 or so unique silhouettes, with the dragged sprites having a public GameObject set to the specific silhouette it is meant to be placed on, and snaps to it if close enough. I am not completely new to coding, and have been working on my project for a few months now, while this tutorial makes complete sense, the added complexity of my mini game (i.e repeating patterns, and sprites) does not quite work. I was hoping to use the same method, or at least one close enough as to not have to make a complex system (for me) for such a minor puzzle/mini game. So my question is, is it possible to set something like a public variable to be any object that contains a specific tag? For instance my goal would be to have something like:
.
public GameObject correctSpace;
.
...on a script for the banked sprites, and when within a certain distance of a black square (which are GameObjects) that contains the tag "HorizontalLine" for example, to say 'OK, this specific instance of this GameObject is the correctSpace GameObject. And likewise forget that info if it was to be moved away. Ideally, it would also be public so I could change it in the inspector for each "puzzle piece" and not have to hard code which tag each unique piece is looking for.
.
Thanks!
Answer by ImKyleConway · Jul 26, 2020 at 12:18 AM
Solved, maybe not the best way but I gave both object box collider 2d/ Rigid Body 2d Components, and the same tag, in this instance, "HLine", then I added this code:
public GameObject correctForm;
public string correctTileType;
void OnCollisionEnter2D(Collision2D collision)
{
if ((collision.gameObject.tag == correctTileType) && (gameObject.tag == correctTileType))
{
correctForm = collision.gameObject;
}
}
Basically I used a public string to be able to tell the script which tag to look for through the inspector (YES!) instead of having 6 different if statements, or god forbid 6 different script all together. There is a Var called "correctForm" which ever object that is set to will allow the banked items to snap to its position. This code checked what the tag of the object I am colliding which is, in this "HLine", and what my objects tag is, also "HLine". And if they are the same, that object I am colliding with becomes the new public GameObject correctForm;. I still have to manually set the tags for the banked objects and the black squares that will accept that shape, but I am happy to avoid hard coding it.