【发布时间】:2019-09-12 00:03:02
【问题描述】:
我正在开发一款战术角色扮演游戏,我有一个名为 Map 的空游戏对象,它由 36 个图块组成。
地图对象附有这个脚本:
using System.Collections.Generic;
using UnityEngine;
public class GridMap : MonoBehaviour
{
private GameObject[] MyVector = new GameObject[36];
public GameObject[,] GridMatrix = new GameObject[6,6];
public GameObject Map;
// Start is called before the first frame update
void Awake()
{
for (int i = 0; i < 36; i++)
{
try
{
MyVector[i] = Map.transform.GetChild(i).gameObject;
}
catch
{
print("Something is wrong!");
}
}
}
void Start()
{
int Counter = 0;
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
{
GridMatrix[i, j] = MyVector[Counter];
Counter;
}
}
}
// Update is called once per frame
void Update()
{
}
}
每个图块都有这个脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tile : MonoBehaviour
{
public bool Current = false;
public bool Selectable = false;
public bool MouseOver = false;
public bool Clicked = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnMouseOver()
{
MouseOver = true;
if (Clicked == false)
{
GetComponent<Renderer>().material.color = Color.red;
}
if (Input.GetMouseButton(0))
{
Clicked = true;
GetComponent<Renderer>().material.color = Color.green;
}
}
void OnMouseExit()
{
MouseOver = false;
Clicked = false;
GetComponent<Renderer>().material.color = Color.white;
}
private void OnTriggerStay(Collider other)
{
if (other.tag == "Player")
{
GetComponent<Renderer>().material.color = Color.magenta;
Current = true;
}
}
private void OnTriggerExit(Collider other)
{
GetComponent<Renderer>().material.color = Color.white;
Current = false;
}
}
我想检测玩家在哪个图块中,例如:如果玩家在矩阵中位置为 0,0 的图块中,我想在控制台中显示如下内容: “玩家在位置 0,0'。
我已经创建了这个脚本并将它附加到播放器上,以便获取它在地图(网格)中的位置,但是它不起作用:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GetPlayerPosition : MonoBehaviour
{
private GameObject mapgrid;
GridMap map;
float tileX, tileY;
// Start is called before the first frame update
void Start()
{
mapgrid = GameObject.FindGameObjectWithTag("map");
map = mapgrid.GetComponent<GridMap>();
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
{
Tile tile = map.GridMatrix[i, j].GetComponent<Tile>();
if (tile.Current)
{
tileX = i;
tileY = j;
Debug.Log(tileX);
Debug.Log(tileY);
}
}
}
}
// Update is called once per frame
void Update()
{
}
}
我能做些什么来解决这个问题? Print of the project. The black cylinder is the player
【问题讨论】:
-
我宁愿使用
OnTriggerEnter.. 使用GetComponent每一帧都相当昂贵... 你能进一步定义however is not working吗? ..据我所知,除了Start之外,它什么也没做... -
脚本 GetPlayerPostion 没有做任何事情。我认为这行代码会起作用,但事实并非如此。
Tile tile = map.GridMatrix[i, j].GetComponent<Tile>(); if (tile.Current) { tileX = i; tileY = j; Debug.Log(tileX); Debug.Log(tileY); } }它显示消息“对象引用未设置为对象的实例” -
查看我的答案.. 错误很可能是由于
GetPlayerPosition的Start称为之前GridMap的,所以数组尚未填充但只有null值。在回答中也提到了