- Home /
Just wondering how I can create a child for each generated hex and make that child a sphere collider? Thanks.
GameObject hex_go = new GameObject(); hex_go.name = "Hex_" + x + "_" + y; hex_go.transform.position = new Vector3(xPos, y * yOffset, 0); hex_go.transform.SetParent(this.transform); hex_go.AddComponent(); hex_go.AddComponent < SphereCollider > ();
This script places a collider on the sprite itself but it forces me to name the entire sprite "Hex Collider" because i need the following script to work. Where as I only want to, in theory, name the collider so that the ray can find it.
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit[] hitInfo = Physics.RaycastAll(ray.origin, ray.direction); foreach (RaycastHit h in hitInfo) { if (h.collider.name == "HexCollider") //the name determines what happens when uncle ray ray strikes it. { //do something Debug.Log("Ray hit someone"); } }
Thanks Heaps!
Answer by Chiroculon · Apr 06, 2017 at 10:03 PM
@redphaze You could do it as follows:
GameObject hex_go = new GameObject();
hex_go.name = "Hex_" + x + "_" + y;
hex_go.transform.position = new Vector3(xPos, y, * yOffset, 0);
hex_go.transform.SetParent(this.transform);
GameObject collider_go = new GameObject();
collider_go.name = "HexCollider";
collider_go.transform.SetParent(hex_go.transform);
collider_go.AddComponent<SphereCollider>();
However, you should consider using a tag or a layer, rather than the object's name, when choosing what to do, because comparing strings is a slower operation.
If you just want to determine whether the hit object is a hex, use a tag.
If you want the trace to ignore some things and not others, use a layer.
Awesome thanks, worked perfectly :) so what would the benefits be for using tags ins$$anonymous$$d? and how would i do that? thanks :) @Chiroculon
I thought that tags weren't strings, but have since realized my mistake. I also thought one could have multiple tags on an object.
A tag does have the advantage that it is independent from the display, so you could have the name be "HexColl_x_y", or something otherwise useful, while the tag remains "HexCollider".
I do not know enough about your project to deter$$anonymous$$e whether implementing a more robust system to identify objects is worthwhile.
Answer by Malleck666 · Apr 06, 2017 at 10:31 AM
Why not create a custom component instead, and check if the gameObject has that attached to it. It would probably prove more useful in the long run too.
$$anonymous$$aybe that would work, I'm a bit new to C# in general but would i be able to name a component separately or is that basically what I'm doing when I add the collider to the sprite?
A custom component would be, for example, your own script. If you had a script called "HexTile" or something, you could check to see if that gameObject has one attached. You can then even use this script to store any values directly related to the Hex Tile.