Unity-在实例化时传递参数

agi*_*iro 3 c# instantiation unity-game-engine

我做了一个简单的消息框,应向用户显示一条消息。它是一个预制件,可以做几件事,大部分是实例化时的动画。为了在实例化时运行代码,我使用了该Start()函数。当我已经知道要传达什么信息时,它就起作用了,但是我需要一个类似的东西constructor,该东西在之前运行Start(),但instantiation可以运行并且可以接受参数。现在,我完全意识到我可以实例化,设置消息并运行所有内容-因此在实例化它的地方使用3行代码,但是我很好奇是否还有另一个更合适的解决方案?我在网上发现的只是实例化,然后做点什么。

编辑:

我要求显示一个消息框:

var timeBox =
    Instantiate(messageBox, penaltySpawnLoc.position, penaltyPrefab.transform.rotation, transform);
    var scr = timeBox.GetComponent<MessageBox>();
    scr.OnCreated(message);
Run Code Online (Sandbox Code Playgroud)

OnCreated进行初始化,显示动画,基本上所有内容。但它需要一个string输入知道什么露面,我不希望设置“对飞”的文本价值-它将使显得有些怪异闪烁时在MessageBox可见,但文本未设置。

编辑2:

最后一个参数transformInstantiationCanvas这个剧本是因为这是一个UI脚本。该参数意味着刚实例化的GameObject是该子对象。

编辑3:

timeBox只是的一个实例messageBox,它们是GameObject。一个消息框仅使用一次。其目的是与消息一起出现,并在0.5秒后消失并移开。离开后,它会自我毁灭。

nik*_*sga 7

我会使用工厂作为消息框,所以像

var timebox = MessageBoxFactory.Create(message);
timebox.Show();
Run Code Online (Sandbox Code Playgroud)

并在工厂类中进行设置并返回消息框

public static MessageBox Create(string message) {
   var newTimeBox = Instantiate(messageBox, penaltySpawnLoc.position, penaltyPrefab.transform.rotation, transform);
   var scr = newTimeBox.GetComponent<MessageBox>();
   scr.SetMessage(message);
   return scr;
Run Code Online (Sandbox Code Playgroud)

其中 Show() 是新的 OnCreated()。我发现这种模式有助于减少调用代码,如果我需要调整我想要的东西的创建方式,那么它就可以与共享工厂代码集中在一个地方。


Pro*_*mer 5

您可以使用函数或扩展方法来执行此操作。

在这种情况下,扩展方法更合适。

我们将使用Object代替一个扩展对象GameObject。由于GameObject继承自Object,因此此扩展方法应同时适用于Object,GameObject和Transform。

创建一个名为的类,ExtensionMethod然后将所有内容粘贴在其下。

using UnityEngine;

public static class ExtensionMethod
{
    public static Object Instantiate(this Object thisObj, Object original, Vector3 position, Quaternion rotation, Transform parent, string message)
    {
        GameObject timeBox = Object.Instantiate(original, position, rotation, parent) as GameObject;
        MessageBox scr = timeBox.GetComponent<MessageBox>();
        scr.OnCreated(message);
        return timeBox;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

Start函数中只有一个线路调用可以处理所有其他任务。

public class Test: MonoBehaviour
{
    GameObject messageBox = null;
    Transform penaltySpawnLoc = null;
    GameObject penaltyPrefab = null;

    void Start()
    {
        gameObject.Instantiate(messageBox, penaltySpawnLoc.position, penaltyPrefab.transform.rotation, transform, "Hello");
    }
}
Run Code Online (Sandbox Code Playgroud)