我有一个脚本在游戏中的随机位置产生猫,当用户点击它们时,它们应该被销毁。然而,我的脚本有问题,并且想知道是否有人知道光线投影有什么问题?
public void CatClick () {
if (Input.GetMouseButtonDown (0)) {
Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast(Ray, out RaycastHit)) {
Destroy(RaycastHit.collider.gameObject);
}
}
}
答案 0 :(得分:1)
你不应该检查更新功能吗?
答案 1 :(得分:1)
另一种方式:
using UnityEngine;
using System.Collections;
public class CatDestructor : MonoBehaviour
{
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
void OnMouseDown()
{
// Destroy game object
Destroy (this.gameObject);
}
}
将此脚本放在" cat"预制,如果你点击它,它将摧毁" cat"。
或 您必须将代码更新为以下功能:
void Update(){
if (Input.GetMouseButtonDown(0)){ // if left button pressed...
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit)){
// the object identified by hit.transform was clicked
// do whatever you want
}
}
}
答案 2 :(得分:0)
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit = Physics2D.GetRayIntersection(ray, Mathf.Infinity);
if (hit.collider != null)
{
// do whatever you want to do here
}
}