Unity c#摧毁用鼠标点击产生的预制
问题描述:
我有一个脚本在游戏中随机位置产生猫,当用户点击它们时,它们应该被销毁。然而,我的脚本遇到了麻烦,并且想知道是否有人知道raycast出了什么问题?Unity c#摧毁用鼠标点击产生的预制
public void CatClick() {
if (Input.GetMouseButtonDown (0)) {
Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast(Ray, out RaycastHit)) {
Destroy(RaycastHit.collider.gameObject);
}
}
}
答
另一种方式做到这一点:
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);
}
}
把这个脚本放在“猫”预制件上,如果你点击它,它会摧毁“猫”。
或者必须把你这样的代码更新功能:
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
}
}
}
答
您不应该检查更新功能吗?
答
像阿恩说,一定要检查它的更新功能,同时如果它是一个2D撞机确保将其更改为
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
}
}