本文介绍了有时onmousedown事件()在Unity方法执行,有时不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我必须连接到四这段代码

So I have this code attached to a Quad.

public class ShapeGrid : MonoBehaviour {

public GameObject[] shapes;

void Start(){
    GameObject[,] shapeGrid = new GameObject[3,3];
    StartCoroutine(UpdateGrid());
}

IEnumerator UpdateGrid(){
    while (true) {
        SetGrid ();
        yield return new WaitForSeconds(2);
    }
}

void SetGrid(){
    int col = 3, row = 3;
    for (int y = 0; y < row; y++) {
        for (int x = 0; x < col; x++) {
            int shapeId = (int)Random.Range (0, 4.9999f);
            GameObject shape = Instantiate (shapes[shapeId]);
            shape.AddComponent<ShapeBehavior>();
            Vector3 pos = shapes [shapeId].transform.position;
            pos.x = (float)x*3;
            pos.y = (float)y*3;
            shapes [shapeId].transform.position = pos;
        }
    }
}



上面的脚本生成的游戏对象在运行时,到我指定的另一个脚本:

The script above generates Game Objects at run time, to which I assigned another script:

public class ShapeBehavior : MonoBehaviour {

    void OnMouseDown(){
        Debug.Log ("Destroy");
        Destroy (gameObject);
    }
}



的问题是,有时onmousedown事件()执行,有时没有。我想不通为什么,以及如何解决它。

The problem is, sometimes the OnMouseDown() executes, sometimes it does not. I cannot figure out why , and how to fix it.

推荐答案

也许你不得不对撞机添加到所有的对象,因为OnMouse事件基于碰撞。以下是详细信息:

Probably you have to add colliders to all of objects because OnMouse events are based on collisions. Here is detailed info: Unity Docs - OnMouseDown

编辑:一些会谈,我们发现,这个问题被实例化法后引起。

after some talks we find out that the problem was caused by Instantiate method.

这是百达更好的方式来填补所有的实例化方法参数如:

It's allways a better way to fill all of parameters in Instantiate method e.g

实例(预制,Vector3.zero,Quaternion.Identity)

如果你愿意,你可以实例化对象后更改这些参数。

if you want, you could change any of these parameters after instantiating object.

这篇关于有时onmousedown事件()在Unity方法执行,有时不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 10:31