仅使用Ray cast和鼠标单击

时间:2016-11-10 18:37:52

标签: c# unity3d

我创建了以下代码,以查看我点击了哪个游戏对象,但是我无法找到如何更改仅单击的对象的材质,它会更改具有该脚本的所有对象的材质。

//Public

public int TileGroup = 0; //Indicates the Tile Group Number.

//Private

public Rigidbody myRigidbody;
public Renderer myRenderer;
public Material tileDefaultMaterial;
public Material tileSelectedMaterial;
public Material tileSameGroupMaterial;

void Start () {
    myRigidbody = GetComponent<Rigidbody> ();
    myRenderer = GetComponent<Renderer> ();
    tileDefaultMaterial = Resources.Load ("TileDefault", typeof(Material)) as Material;
    tileSelectedMaterial = Resources.Load ("TileSelected", typeof(Material)) as Material;
    tileSameGroupMaterial = Resources.Load ("TileSameGroup", typeof(Material)) as Material;
}

void Update () {
    if (Input.GetMouseButtonDown (0)) {
        TileClick ();
    }
}

void TileClick (){

    RaycastHit hitInfo = new RaycastHit ();
    bool hit = Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hitInfo);

    if (hit) {
        Debug.Log ("Hit: " + hitInfo.transform.gameObject.name);
    }

    if (hitInfo.transform.gameObject.tag == "Tile") {
        Debug.Log ("Hit a Tile!");
        myRenderer.material = tileSelectedMaterial;
    } else {
        Debug.Log ("Hit Empty Space!");
    }
}

1 个答案:

答案 0 :(得分:0)

正在运行

void Update()
{
    if(Input.GetMouseButtonDown(0))
    {
        TileClick();
    }
}

无论何时单击(无论在何处),Input.GetMouseButton(0)都将在所有脚本实例中都为true。所以你最终改变了所有对象的颜色。 相反,您可以尝试使用OnMouseDown()方法。

void OnMouseDown() 
{
    TileClick();
}