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)。 –