【问题标题】:Refactoring Code in Unity by not using the inspector不使用检查器在 Unity 中重构代码
【发布时间】:2017-06-20 01:41:56
【问题描述】:

我的统一游戏中有一个传送门。通过输入触发器,它应该加载一个场景。所以这段代码真的很短,这里是:

public class PortalData : EnvironmentCommonData // the data class with some information
{
    public PortalData(string sceneToLoad) // set the scene in the constructor
    {
        SceneToLoad = sceneToLoad;
    }

    public string SceneToLoad { get; set; } // the scene to load when entering
}

public class PortalController : EnvironmentCommonController // the portal class
{
    [SerializeField]
    string sceneToLoad; // set the scene in the inspector

    private PortalData data;

    private void Start()
    {
        data = new PortalData(sceneToLoad); // instance for the data class
    }

    private void OnTriggerEnter(Collider col) // player enters the trigger
    {
        if (CheckCollision(col, data.PlayerObject)) // is the entering object the player?
            LoadScene(data.SceneToLoad); // load the new scene
    }
}

所以我正在寻找一种不使用检查器的聪明方法。我想让这一切都由脚本自动化。

所以我尝试设置控制器抽象并创建从该控制器继承的不同控制器类,但这并不优雅。

这里你可以看到我尝试的一个例子:

https://hastebin.com/utuqubafuz.cs

有人有想法吗?

完美的脚本应该是这样的

public class Portal : Monobehaviour
{
    string sceneToLoad = "";

    void OnTriggerEnter(Collider col)
    {
        if(col.gameObject.tag == "Player")
            LoadScene(sceneToLoad);
    }
}

但如果可能的话,我不想要检查员。

【问题讨论】:

  • 您必须在某处创建它们。如果您已经在场景中生成了它们,只需使用检查器。如果您使用代码创建它们,那就是,您将在其中指定字符串。
  • 您想从运行时生成sceneToLoad 变量的值吗?如果是这样,你的场景的名称是什么?

标签: c# unity3d


【解决方案1】:

您可以让PortalSpawner 实例化GameObjects,通过AddComponent()Portal 对象附加到它们,并设置string newPortal.sceneToLoad。虽然这可以避免使用 Inspector 设置字符串,但它仍然需要您在某处指定字符串,正如评论中提到的 @Draco18s。

其他方法是:

  1. 每个场景的子类都明确声明了string sceneToLoad
  2. 为不同位置的同一场景重复使用预制件,
  3. 如果您想避免写 string,您可以使用 enum 并检查每个枚举值并相应地加载场景(代码看起来更脏,但可能会使 Inspector 更干净),或者
  4. 制作一个 JSON 文件(或任何其他数据库或可序列化文本),在其中存储要生成的 Portal 对象的位置,string newPortal.sceneToLoad 每个对象都应包含这些位置。最终这将回到AddComponent() 方法。

JSON 方法可能更接近您正在寻找的方法,但它需要更多的工作,我不确定是否值得努力。

如果这些不是您正在寻找的解决方案,请提供您希望在哪些步骤实现自动化。 sceneToLoad 无论如何都必须在某个点指定。我相信 Inspector 字段是 Unity 中执行此操作的常见位置。

另一方面,坚持场景命名约定可能会使某些过程更容易。例如,场景名称必须是sceneNumber_k,其中k 是场景的索引,第k 个Portal 将打开第k 个场景。使用这种命名约定,一些初始化字符串的过程可能会自动

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    相关资源
    最近更新 更多