I am trying to follow the CatLikeCoding tutorial on hex maps link text
Fairly early on they label all of the cells by creating a GameObject with a text component, which they then turn in to a prefab. I do this in the usual way (dragging the GameObject to the prefabs folder). But when they come to use the prefab in code, it is used like this:
public class HexGrid : MonoBehaviour
{
public int width = 6;
public int height = 6;
public HexCell cellPrefab;
public Text cellLabelPrefab;
HexCell[] cells;
Canvas gridCanvas;
void CreateCell(int x, int z, int i)
{
......
Text label = Instantiate<Text>(cellLabelPrefab);
label.rectTransform.SetParent(gridCanvas.transform, false);
label.rectTransform.anchoredPosition =
new Vector2(position.x, position.z);
label.text = x.ToString() + "
" + z.ToString();
}
I’m finding that I cannot assign the prefab in the editor, because the type is Text, rather than GameObject. They also use the components directly, rather than using GetComponent<>() which is what I would usually do. What am I missing here, is there a way to create prefabs of types other than GameObjects, or to use prefabs as seen in the code here? It would definitely save some lines of code calling GetComponent and having local variables, but I have never seen this done before and can’t get it to work.
Any help appreciated.
,I am trying to follow the CatLikeCoding tutorial here
I am confused by the part where they make labels for the cells - the label is just a game object with the text component, which they then turn in to a prefab.
When they come to use the label prefab in code, though, it is used like this, where the prefab has a type of Text:
public class HexGrid : MonoBehaviour
{
public int width = 6;
public int height = 6;
public HexCell cellPrefab;
public Text cellLabelPrefab;
HexCell[] cells;
Canvas gridCanvas;
void CreateCell(int x, int z, int i)
{
...
Text label = Instantiate<Text>(cellLabelPrefab);
label.rectTransform.SetParent(gridCanvas.transform, false);
label.rectTransform.anchoredPosition =
new Vector2(position.x, position.z);
label.text = x.ToString() + "
" + z.ToString();
}
Normally I would have had my public variable be a GameObject which I can assign in the editor, and then get the text and rectTransform components using GetComponent<>(). When I try and follow the tutorial, it unsurprisingly won’t let me assign my prefab to the public cellLabelPrefab in the editor because it has the wrong type.
What am I missing? Is there a way to use prefabs as described in this tutorial? If so it would save a lot of uses of GetComponent, but I have never seen it done this way and can’t get it to work.
Any help or advice appreciated.