首页 > 解决方案 > 实例化制作多个克隆

问题描述

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

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");
        }
    }
}

标签: unity3dclone

解决方案


推荐阅读