0
我想創建一個小型戰列艦遊戲。我想用OnMouseEnter事件懸停單元格,但沒有任何反應,事件從未被調用。Unity Battleships - 改變遊戲對象的顏色
我將代碼分爲3個腳本,數據,控制器和視圖。
我的數據保持信息:
public class CellCommonData : MonoBehaviour // Datastore
{
public bool IsShipCell { get; set; } // is a ship there?
public bool WasActivated { get; set; } // cell already clicked
[SerializeField]
private Color defaultColor; // default Color -> light blue
public Color DefaultColor { get { return defaultColor; } }
[SerializeField]
private Color mouseOverColor; // hover Color -> dark blue
public Color MouseOverColor { get { return defaultColor; } }
[SerializeField]
private Color hitColor; // hit Color -> green
public Color HitColor { get { return defaultColor; } }
[SerializeField]
private Color noHitColor; // no Hit -> red
public Color NoHitColor { get { return defaultColor; } }
private void Start()
{
WasActivated = false; // the cell is not clicked on Start
}
}
我的控制器將處理玩家的行動:
public class CellCommonController : MonoBehaviour
{
private CellCommonData cellData;
private CellCommonView cellView;
private void Start()
{
cellData = GetComponent<CellCommonData>();
cellView = GetComponent<CellCommonView>();
}
private void OnMouseDown() // Cell clicked
{
if (!cellData.WasActivated) // Cell was not clicked before
{
if (cellData.IsShipCell) // ship hit?
{
cellView.SetCellColor(cellData.HitColor);
}
else // No ship there
{
cellView.SetCellColor(cellData.NoHitColor);
}
cellData.WasActivated = true; // Cell got clicked
}
}
}
和視圖處理單元的 「看」:
public class CellCommonView : MonoBehaviour
{
private CellCommonData cellData;
private Renderer cellRenderer;
private void Start()
{
cellData = GetComponent<CellCommonData>();
cellRenderer = GetComponent<Renderer>();
SetCellColor(cellData.DefaultColor); // colorize the cell with the default Color
}
public void SetCellColor(Color color) // Change the cells color
{
cellRenderer.material.SetColor("_Color", color);
}
private void OnMouseEnter() // cell got hovered
{
if (!cellData.WasActivated) // not clicked
{
SetCellColor(cellData.MouseOverColor);
}
}
private void OnMouseExit() // leave the cell
{
if (!cellData.WasActivated) // not clicked
{
SetCellColor(cellData.DefaultColor);
}
}
}
我唯一的問題是,事件OnMouseEnter()
和OnMouseExit()
是ne ver叫。但我不明白,那裏出了什麼問題。
這裏是它的照片:
你當你調用這個方法時,你不必調用任何東西,你必須把它和你正在調用的東西放在一起 –
把Debug.Log放在OnMouseEnter()和OnMouseExit()之前,然後說它們不是調用。 – Programmer
爲什麼你會讓你的模特班成爲MonoBehaviour?而你的問題很可能是缺少這個gameobject上的3d對撞組件。 –