IEnumerator和鼠标单击放置块的问题

时间:2019-05-14 23:02:46

标签: c# unity3d

我正在尝试创建一个块放置脚本,该脚本每0.15秒放置一个块,并且效果很好。问题是,当我尝试执行相同的操作来破坏块时:它不是每隔0.3秒破坏一次块,而是等待0.3秒,然后每帧破坏一次。

我该如何解决?我尝试将其放在其他脚本中,但似乎也不起作用。奇怪的是,如果我在Debug.Log("1")内添加void Place(){ Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hitInfo; if(Physics.Raycast(ray, out hitInfo)){,则会每帧打印1。但是,如果我将Debug.Log("1")放在if (hitInfo.collider == up){内,它将每0.3秒打印一次1

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class placeBlock : MonoBehaviour
{
    public GameObject cube;
    public Collider up;
    public Collider bottom;
    public Collider right;
    public Collider left;
    public Collider front;
    public Collider back;

    void Start(){}

    void Update()
    {
        if(Input.GetMouseButton(0)){
            StartCoroutine(MyMethod());
        }

        if(Input.GetMouseButton(1)){
            StartCoroutine(MyMethod2());
        }
    }

    void Place2()
    {   
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hitInfo;
        if(Physics.Raycast(ray, out hitInfo))
        {
            Destroy(hitInfo.transform.parent.gameObject);
        }
    }



    void Place()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hitInfo;
        if(Physics.Raycast(ray, out hitInfo)){
            if (hitInfo.collider == up){
                Instantiate(cube,new Vector3(this.transform.position.x,this.transform.position.y + 1,this.transform.position.z), Quaternion.identity);
            }
            if (hitInfo.collider == bottom){
                Instantiate(cube,new Vector3(this.transform.position.x,this.transform.position.y - 1,this.transform.position.z), Quaternion.identity);
            }
            if (hitInfo.collider == right){
                Instantiate(cube,new Vector3(this.transform.position.x - 1,this.transform.position.y,this.transform.position.z), Quaternion.identity);
            }
            if (hitInfo.collider == left){
                Instantiate(cube,new Vector3(this.transform.position.x + 1,this.transform.position.y,this.transform.position.z), Quaternion.identity);
            }
            if (hitInfo.collider == front){
                Instantiate(cube,new Vector3(this.transform.position.x,this.transform.position.y,this.transform.position.z - 1), Quaternion.identity);
            }
            if (hitInfo.collider == back){
                Instantiate(cube,new Vector3(this.transform.position.x,this.transform.position.y,this.transform.position.z + 1), Quaternion.identity);
            }
        }
    } 

    IEnumerator MyMethod()
    {
        yield return new WaitForSeconds(0.15F);
        Place();
    }

    IEnumerator MyMethod2()
    {
        yield return new WaitForSeconds(0.3F);
        Place2();
    }
}

0 个答案:

没有答案