在unitgy3D里,我想做一个点击一个在运行后被我写的随机方块生成器生成的方块,会在控制台报出其在20207的随机生成器里的xyz坐标,左键单点是读出坐标,左键双击是在该位置的上方生成预制体宫殿。代码如下
```c#
using UnityEngine;
using UnityEngine.EventSystems;
public class StoneGenerator : MonoBehaviour
{
public GameObject stonePrefab; // 石头的预制体
public GameObject grassPrefab; // 草的预制体
public GameObject palacePrefab; // 宫殿的预制体
public static float spacing = 2f; // 方块间距
public int length = 20; // 生成区域的长度
public int width = 20; // 生成区域的宽度
public int height = 7; // 生成区域的高度
[Range(0f, 1f)]
public float[] spawnChances; // 每层岩石方块生成的概率
public int seed; // 地图种子
public float additionalSpawnChance = 0.006f;
void Start()
{
Random.InitState(seed);
GenerateStones();
}
void GenerateStones()
{
// 遍历生成区域的每个方块
for (int y = 0; y < height; y++)
{
for (int x = 0; x < length; x++)
{
for (int z = 0; z < width; z++)
{
// 根据每层的生成概率来生成岩石方块
if (y == 4) // 规律1:当y=4时,必定生成草方块。
{
Vector3 spawnPosition = new Vector3(x * spacing, y * spacing, z * spacing);
Instantiate(grassPrefab, spawnPosition, Quaternion.identity, transform);
}
else if (Random.value < spawnChances[y]) // 当前位置按概率生成石头方块
{
Vector3 spawnPosition = new Vector3(x * spacing, y * spacing, z * spacing);
GameObject blockObject = Instantiate(stonePrefab, spawnPosition, Quaternion.identity);
blockObject.transform.SetParent(transform);
blockObject.AddComponent<BlockEventListener>();//给我代码的人说这附近有可以引用其他脚本的代码
if (y == 5 && Random.value < additionalSpawnChance) // 在y=5处的岩石方块上方生成岩石方块的概率判断
{
Vector3 spawnPositionAbove = new Vector3(x * spacing, (y + 1) * spacing, z * spacing); // 上方生成岩石方块
GameObject blockObjectAbove = Instantiate(stonePrefab, spawnPositionAbove, Quaternion.identity);
blockObjectAbove.transform.SetParent(transform);
}
}
}
}
}
}
}
using UnityEngine;
using UnityEngine.EventSystems;
public class BlockEventListener : MonoBehaviour, IPointerClickHandler
{
public void OnPointerClick(PointerEventData eventData)
{
Debug.Log(1);
StoneGenerator stoneGenerator = FindObjectOfType<StoneGenerator>(); // 获取 StoneGenerator 脚本实例
Debug.Log(2);
if (stoneGenerator != null)
{
Debug.Log(3);
Vector3 blockPosition = transform.position / StoneGenerator.spacing;
int x = Mathf.FloorToInt(blockPosition.x);
int y = Mathf.FloorToInt(blockPosition.y);
int z = Mathf.FloorToInt(blockPosition.z);
Debug.LogFormat("Clicked block position in StoneGenerator: ({0}, {1}, {2})", x, y, z);
Debug.Log(4);
}
}
}

上图可以展示第二个脚本被挂载在一个物体下,并且该物体有collider。用途不明(有人说这么做)

上图可以展示第一个脚本被挂载在空物体上,用来生成随机地图块。

上图可以展示被随机生成的方块各自都有collider。
我想要的效果是:左键单击方块,控制台报出其在随机生成器里的坐标。
通过第二段代码,经我试验,发现4个用来检测是否有运行的Debug.Log输出数字,结果运行后点击屏幕,一个数字都没出来。
如果可以的话,能不能给个左键双击方块,在该方块的上方,即y+1处生成宫殿的代码

