在随机位置生成实例化对象



我试图在某些边界内的随机位置生成多个对象,但这些对象看起来离得太近,而且它们总是出现在边界的左侧。

这是我用来生成对象(单词(的代码:

while (a < words2.Length)
{
wordOutput = Instantiate(wordOutputPrefab) as GameObject;
wordOutputPrefab.GetComponentInChildren<TextMeshPro>().text = words2[a];
wordOutputPrefab
.GetComponentInChildren<TextMeshPro>()
.GetComponentInChildren<RectTransform>()
.position = new Vector3(
UnityEngine.Random.Range(0, 4),
UnityEngine.Random.Range(-4, 4),
0);
a++;
}

这些物体(单词(就是这样出现在屏幕上的:在此处输入图像描述

第一个UnityEngine.Random.Range(0, 4);将给您0、1、2或3。如果你想有浮动,你还需要给出像这样的浮动值UnityEngine.Random.Range(0f, 4f);

此外,不应将.position用于RectTransforms,而应使用.rect.localposition.anchoredPosition。什么是最好的实际上取决于你的画布和UI的结构!

最新更新