[英]How can i add a BehaviourScript to an Instantiated GameObject in Unity3D?
我正在開發一個游戲,您可以在其中使用鼠標左鍵實例化多維數據集。 現在,我想使用箭頭鍵旋轉這些實例化的多維數據集。 我想知道如何將以下代碼與實例化多維數據集連接起來! (我的實例化多維數據集被保存在列表列表中。)
我的輪換代碼:
if (Input.GetKey (KeyCode.LeftArrow))
{
transform.Rotate(0, 0, rotationAngle * Time.deltaTime, Space.World);
}
if (Input.GetKey (KeyCode.RightArrow))
{
transform.Rotate(0, 0, - rotationAngle * Time.deltaTime, Space.World);
}
將代碼放在腳本中,並命名為RotateOnKeys之類的名稱,然后在實例化多維數據集的腳本中執行以下操作:
// This is the line of code that you're already using to spawn a cube:
GameObject cube = GameObject.Instantiate(cubePrefab) as GameObject;
// This is the line of code needed to attach a script:
cube.AddComponent<RotateOnKeys>();
與大多數與編程相關的事情一樣,有幾種方法可以實現。
首先,您要將其放在MonoBehaviour中。 具體來說,您可能希望在Update()循環中使用它。 像這樣:
public class SpinGameObject : MonoBehaviour
{
void Update()
{
if (Input.GetKey (KeyCode.LeftArrow))
{
transform.Rotate(0, 0, rotationAngle * Time.deltaTime, Space.World);
}
if (Input.GetKey (KeyCode.RightArrow))
{
transform.Rotate(0, 0, - rotationAngle * Time.deltaTime, Space.World);
}
}
}
如果要在所有多維數據集上使用此功能,則可以將其直接附加到實例化的預制件上。
否則,如果您希望選擇將其應用於哪些多維數據集,則可以獲取實例化的包含多維數據集的GameObject,然后調用以下函數:
void AttachScriptToGameObject(GameObject go)
{
go.AddComponent<SpinGameObject>();
}
希望有幫助!
編輯:很多人都在回應,所有這些工作:)
好吧,您正在尋找一種叫做Prefab的東西。 預制是預制的對象,您可以向其添加腳本等,然后就可以實例化此預制 。 預制教程鏈接
編輯或者,您也可以使用@Jayson Ash方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.