实例化多个克隆

时间:2019-03-25 13:57:26

标签: unity3d clone

我正在游戏中构建建筑系统,并且基本机制起作用了,但是由于某种原因,每当我放下对象时,它每次放置都会增加更多的克隆。第一个放置创建一个克隆,第二个放置创建两个克隆,第三个,三个克隆,依此类推。我通过将其从具有所有建筑物预制件的空游戏对象中移出来修复了一个对象,但这仅适用于该对象。

using UnityEngine;
using UnityEngine.AI;

public class GroundPlacementController : MonoBehaviour
{
    [SerializeField]
    private GameObject placeableObjectPrefab;

    [SerializeField]
    private KeyCode newObjectHotkey = KeyCode.A;

    public NavMeshObstacle nav;

    private GameObject currentPlaceableObject;

    private float mouseWheelRotation;

    private void Update()
    {
        HandleNewObjectHotkey();
        nav = GetComponent<NavMeshObstacle>();
        if (currentPlaceableObject != null)
        {
            MoveCurrentObjectToMouse();
            RotateFromMouseWheel();
            ReleaseIfClicked();
        }
    }

    private void HandleNewObjectHotkey()
    {
        if (Input.GetKeyDown(newObjectHotkey))
        {
            if (currentPlaceableObject != null)
            {
                Destroy(currentPlaceableObject);                   
            }
            else
            {
                currentPlaceableObject = Instantiate(placeableObjectPrefab);
            }
        }
    }

    private void MoveCurrentObjectToMouse()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        RaycastHit hitInfo;
        if (Physics.Raycast(ray, out hitInfo))
        {
            currentPlaceableObject.transform.position = hitInfo.point;
            currentPlaceableObject.transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
            currentPlaceableObject.GetComponent<NavMeshObstacle>().enabled = false;
        }
    }

    private void RotateFromMouseWheel()
    {
        Debug.Log(Input.mouseScrollDelta);
        mouseWheelRotation += Input.mouseScrollDelta.y;
        currentPlaceableObject.transform.Rotate(Vector3.up, mouseWheelRotation * 90f);
    }

    private void ReleaseIfClicked()
    {
        if (Input.GetMouseButtonDown(0))
        {                
            currentPlaceableObject.GetComponent<NavMeshObstacle>().enabled = true;
            print("disabled");
            currentPlaceableObject = null;
            print("removed prefab");
        }
    }
}

0 个答案:

没有答案