unity3d - 实例化制作多个克隆
问题描述
我在我的游戏中制作了一个建筑系统,基本的机制是有效的,但是由于某种原因,每当我放下物体时,它会随着每个放置逐渐增加更多的克隆。第一个放置创建一个克隆,第二个放置创建两个克隆,第三个放置创建三个克隆,依此类推。我通过将其移出一个空的游戏对象来为一个对象修复它,该对象在层次结构中具有所有建筑预制件,但它仅适用于此。
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");
}
}
}
解决方案
推荐阅读
- reporting-services - SSRS express 2017,配置管理器不连接服务;RPC 问题
- jquery - Django - TypeError - NoneType' 对象不可迭代 - 不明白为什么 Object 被识别为 None
- ruby-on-rails - 如何在 Rails 中使用 Simple Form 仅显示一组特定的嵌套属性?
- ruby-on-rails - Rails:使用模型中的常量将实例方法定义为关注点
- php - 更新表并捕获用户注销时的注销时间
- javascript - 在小屏幕上隐藏/显示图像
- python - TensorFlow:使用 Python 确定 tensorRT 功耗
- c# - Configuration.GetSection("ConnectionStringName").Get始终为空
- ms-access - MS Access - 登录
- mysql - 重写一个嵌套的mysql查询以创建一个视图