在gameobject实例化GameObject

时间:2018-04-28 23:04:24

标签: c# unity3d

嘿,我想知道如何在另一个Public Transform上实例化Public GameObject?

如果我想在GUI.Button按下实例化,请执行

If(GUI.Button(new Rect(Screen.width / 2, Screen.height / 2 + 100, 100, 25), "Test"))
{
    Instantiate(mag, transform.position, transform.rotation)
}

这是我的剧本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GunScript : MonoBehaviour {

    public GameObject Gun;

    public Transform magTransform;
    public GameObject mag;

    // Use this for initialization
    void Start ()
    {   
    }

    // Update is called once per frame
    void Update ()
    {

        if(Input.GetKeyDown(KeyCode.U))
        {
            Instantiate(mag, transform.magTransform, transform.rotation);
        }
    }

    private void OnGUI()
    {
        GUI.Button(new Rect(Screen.width / 2, Screen.height / 2 + 100, 100, 25), "Test");
    }
}

1 个答案:

答案 0 :(得分:2)

  

我想知道如何在另一个Public上公开Game GameObject   变换

我认为magTransform是其他变换。要在mag转换的位置上实例化magTransform预制件,只需使用magTransform.positionmagTransform.rotation

只需更改

Instantiate(mag, transform.magTransform, transform.rotation);

Instantiate(mag, magTransform.position, magTransform.rotation);
  

如果我想在GUI上实例化,请按

请勿使用GUI.XXX API或需要放置在OnGUI函数中的任何内容。例外情况是你制作一个编辑器插件。使用新的UI系统,然后注册到UI Button事件,以便在单击时获得通知。您可以在Unity website上找到UI系统的简单官方教程。

使用正确的UI系统,您的代码应如下所示:

public GameObject Gun;

public Transform magTransform;
public GameObject mag;


public Button instantiateButton;

void OnEnable()
{
    //Register Button Events
    instantiateButton.onClick.AddListener(() => buttonCallBack(instantiateButton));
}

private void buttonCallBack(Button buttonPressed)
{
    if (buttonPressed == instantiateButton)
    {
        //Your code for Instantiate button 
        Instantiate(mag, magTransform.position, magTransform.rotation);
    }
}

void OnDisable()
{
    //Un-Register Button Events
    instantiateButton.onClick.RemoveAllListeners();
}