C# 通过不使用检查器在Unity中重构代码
我的统一游戏中有一个门户。通过输入触发器,它应该加载一个场景。这段代码很短,如下所示:C# 通过不使用检查器在Unity中重构代码,c#,unity3d,C#,Unity3d,我的统一游戏中有一个门户。通过输入触发器,它应该加载一个场景。这段代码很短,如下所示: public class PortalData : EnvironmentCommonData // the data class with some information { public PortalData(string sceneToLoad) // set the scene in the constructor { SceneToLoad = sceneToLoa
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
}
}
因此,我正在寻找一种聪明的方法,不使用检查器。我想通过脚本将其全部自动化
因此,我尝试设置控制器抽象并创建不同的控制器类继承自该控制器,但这并不优雅
在这里,您可以看到我尝试的一个示例:
有人有主意吗
好吧,完美的剧本应该是这样的
public class Portal : Monobehaviour
{
string sceneToLoad = "";
void OnTriggerEnter(Collider col)
{
if(col.gameObject.tag == "Player")
LoadScene(sceneToLoad);
}
}
但如果可能的话,我不想让检查器。您可以让
PortalSpawner
实例化游戏对象
s,通过AddComponent()
将门户
对象附加到它们,然后设置字符串newPortal.sceneToLoad
。虽然这样可以避免使用Inspector设置字符串,但仍然需要在某个地方指定字符串,如注释中提到的@Draco18s
其他方式将是:
字符串sceneToLoad
的每个场景的子类string
,可以使用enum
检查每个enum值,并根据需要加载场景(代码看起来会更脏,但可能会使检查器更干净),或者Portal
对象的位置,其中string newPortal.sceneToLoad
每个对象都应该包含。最终,这将返回到AddComponent()
方法sceneToLoad
。我相信督察区是统一进行这项工作的常见场所
另一方面,坚持场景命名约定可能会使某些过程更容易。例如,场景名称必须是
sceneumber_k
,其中k
是场景的索引,第k个门户将打开第k个场景。使用这种命名约定,初始化字符串的某些过程可能会自动进行。您必须在某个地方创建它们。如果已经在场景中生成了它们,只需使用检查器即可。如果您是使用代码创建它们的,那么您应该在那里指定字符串。是否要从运行时生成sceneToLoad
变量的值?如果是,你的场景名称是什么?