Greetings, everyone. I’m new to Unity development, and I’ve been watching lots of tutorials lately. I appreciate the help in advance; answers provided here have helped a lot.
I’ve put together some rudimentary code–I’m just testing some things right now–but I’m stuck because I know before I even finish that there must be a better way to do what I want to do. Here’s what I’m planning:
A hex-based tile board that instantiates an object in the center of whichever hex tile is touched.
I’m currently using the mouse in place of a touch screen, but this is just test code, anyway. I’ve figured out how to spawn the object in the center of the container I touched (a simple 3D cylinder for testing). But here’s where I’m stuck:
I could create a unique name for each of the 19 hex tiles I intend to have in the end, and then just copy/paste this code 19 times for each container. However, I know there has to be a better way, something like grabbing the child GameObject of the Collider hit by the Ray and Instantiating the “sphere” on that specific child, but I can’t figure out how to make it work. Any ideas?
In Unity, I’ve got an EmptyGameObject called “SpawnPoint” as a child of the Cylinder, and that’s where I’m aiming to spawn the sphere. Right now I’m cheating by using a Vector3 to put the sphere where I want it, but that’s just me practicing.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public GameObject sphere;
public GameObject cylinder;
void Update ()
{
if (Input.GetButtonDown("Fire1"))
{
RaycastHit hitInfo;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hitInfo))
{
Debug.Log ("Raycast hit:" + hitInfo.collider.gameObject.name);
if (hitInfo.collider.gameObject.name == "Cylinder")
{
Vector3 spawnPoint = new Vector3 (cylinder.transform.position.x, cylinder.transform.position.y, -200.0f);
Instantiate (sphere, spawnPoint , transform.rotation);
}
}
}
}
}