首页 > 解决方案 > C# Unity:用“部分名称+编号”输入类的子值

问题描述

我从课堂上检索了号码。现在我想通过后者输入选项:

float CarLevel = Settings.LevelSelected; // from main get the level

var LevelNumber = Settings.(LevelOfCar+CarLevel); //enter in corret level

float Kmh = LevelNumber.Kmh; //get the par of level

显然它不能像这样工作......我怎样才能避免一个大经典 IF LEVEL IS 2 ELSE .... 对于所有级别?提示?

标签: c#unity3d

解决方案


我会建议一种更面向对象的方法。

考虑以下

public class Level : ScriptableObject
{
    public int CarLevel;
    public float Kmh;
    // other variables that are shared across all levels
}

如果您需要共享相同脚本的每个级别的特定代码,则可以使用继承。

public class SpecificLevel : Level
{
    public void DoSomething()
    {

    }
}

有一个包含所有级别的经理类。

public class LevelManager : MonoBehaviour
{
    // Assign levels here through the inspector
    public List<Level> Levels;

    public void LoadLevel()
    {
        Level level = Levels.First(x => x.CarLevel == Settings.LevelSelected);
        // Do whatever you want with your level
    } 
}

您将需要使用添加 linq。

using System.Linq;

如果您不了解可编写脚本的对象,我建议您遵循这个简短的教程。它将极大地帮助您的发展。


推荐阅读