【发布时间】:2018-03-20 00:11:51
【问题描述】:
我一直在搜索很多相关问题,但我仍然无法弄清楚为什么我的 OnMouseUp() 不起作用。
我想使用脚本 Mover 在通过左键单击对象选择游戏对象时将其抬起并在任意位置右键单击将其取消。
这里是游戏对象的信息。它确实有一个对撞机,所以我不知道我哪里做错了。
这是 Mover 的代码。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mover : MonoBehaviour {
private bool selected;
// Use this for initialization
void Start () {
selected = false;
}
// Update is called once per frame
void Update () {
Vector3 pos = GetComponent<Rigidbody>().position;
if (Input.GetMouseButtonUp(1) && selected)
{
GetComponent<Rigidbody>().position = new Vector3(pos.x, pos.y - 1f, pos.z);
selected = false;
}
}
void OnMouseUp()
{
Vector3 pos = GetComponent<Rigidbody>().position;
if (!selected)
{
GetComponent<Rigidbody>().position = new Vector3(pos.x, pos.y + 1f, pos.z);
selected = true;
}
Debug.Log("OnMouseUp!");
}
}
debug.log 也没有显示出来。
---更新---
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Mover : MonoBehaviour, IPointerEnterHandler
{
private bool selected;
void Start () {
selected = false;
addPhysicsRaycaster();
}
void Update () {
Vector3 pos = GetComponent<Rigidbody>().position;
if (Input.GetMouseButtonUp(1) && selected)
{
GetComponent<Rigidbody>().position = new Vector3(pos.x, pos.y - 1f, pos.z);
selected = false;
}
}
void addPhysicsRaycaster()
{
PhysicsRaycaster physicsRaycaster = GameObject.FindObjectOfType<PhysicsRaycaster>();
if (physicsRaycaster == null)
{
Camera.main.gameObject.AddComponent<PhysicsRaycaster>();
}
}
public void OnPointerEnter(PointerEventData eventData)
{
Vector3 pos = GetComponent<Rigidbody>().position;
if (!selected)
{
GetComponent<Rigidbody>().position = new Vector3(pos.x, pos.y + 1f, pos.z);
selected = true;
}
Debug.Log("OnPointerEnter!");
}
}
【问题讨论】:
-
不要使用任何
OnMouseXXX函数。使用OnPointerEnter。参见副本中的#6。 -
@Programmer 您好,我尝试了 OnPointerEnter 和 OnPointerDown,但仍然无法正常工作,您能否检查一下我在更新区域中的代码?
-
您的代码现在看起来不错。您是否将
PhysicsRaycaster附加到相机?你必须这样做!请参阅副本以了解如何从代码中执行此操作 -
只需将图形光线投射器添加到相机中,没有很好的文档记录,但需要该组件才能将 3d 世界与事件系统联系起来(您还需要在场景中使用事件系统)
-
@Programmer 非常感谢你这么耐心地教我!