0
我想能够实例化鼠标所在的对象。我试图做到这一点(下面的代码),但在我的尝试中,对象总是在屏幕中心产生。我能做些什么来解决这个问题?如何在鼠标光标处产生对象
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CraftingControl : MonoBehaviour
{
public GameObject[] selectedObjectArray = new GameObject[3];
public GameObject selectedObject;
// Use this for initialization
void Update()
{
if (selectedObject == null)
{
return;
}
if (Input.GetMouseButtonDown(0))//Here im getting postion and spawning objects
{
Vector3 tempMousePost = Input.mousePosition;
Vector3 mousePost = Camera.main.ScreenToWorldPoint(tempMousePost);
mousePost.y = 0;
Instantiate(selectedObject, mousePost, transform.rotation);
}
}
void OnGUI()
{
if (Input.GetKey(KeyCode.C))
{
GUI.Box(new Rect(100, 100, 300, 300), "Crafting");
if (GUI.Button(new Rect(125, 125, 100, 50), "Campfire"))
{
selectedObject = selectedObjectArray[0];
}
if (GUI.Button(new Rect(125, 200, 100, 50), "Tent"))
{
selectedObject = selectedObjectArray[1];
}
if (GUI.Button(new Rect(125, 275, 100, 50), "Fence"))
{
selectedObject = selectedObjectArray[2];
}
}
}
}
你构建一个2D或3D游戏? – pasotee
@pasotee将一个2D物体放入一个3d世界将会很有趣,特别是如果我们不知道它应该如何放置的话。 –
您不应该在游戏开发中使用'OnGUI'(又名“立即模式GUI”)。它仅用于创建编辑器控件您需要使用新的[UI系统](https://docs.unity3d.com/Manual/UISystem.html)。 –