c# - 如何指定动态默认值

标签 c# unity3d

这里是 C# 的新手......试图弄清楚下面的 new GameObject[20, 20] 如何实际引用私有(private)属性值而不是硬编码值。

private int xRadius = 20;
private int yRadius = 20;

private GameObject [,] grid = new GameObject[20, 20];

我试过 this.xRadiusself.xRadius 的变体,但没有成功。我该怎么做?

最佳答案

您不能在类的变量声明范围内使用 this,因为此时没有理由在 grid< 之前定义 xRadius/

您可以通过将 xRadiusyRadius 声明为常量来实现您想要的(常量是不可变的变量,在运行时不会改变);

private const xRadius = 20;
private const yRadius = 20;

private GameObject[,] grid = new GameObject[xRadius, yRadius];

或者将它们标记为静态变量(静态变量存在于任何类实例之外,并且在任何类实例消失后可用);

class Example {
    private static xRadius = 20;
    private static yRadius = 20;

    private GameObject[,] grid = new GameObject[Example.xRadius, Example.yRadius];

或者您可以在类构造函数中定义网格并使用普通类变量引用;

class Example {
    public Example() {
        this.grid = new GameObject[this.xRadius, this.yRadius];
    }
}

最快的解决方案(就运行时较少的资源使用而言)是使用constants,因为值将在编译时被复制并且它们不会占用任何额外的资源,最动态的解决方案是设置它们在构造函数中或在您访问网格对象之前这将允许您在运行时更改 xRadiusyRadius 并重新初始化 grid 变量使用相同的半径变量。

关于c# - 如何指定动态默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37780156/

相关文章:

c# - 如何在负索引处启动数组 C#(UNITY)

c# - "SystemInfo.deviceUniqueIdentifier"在 Android 构建中使用什么?

c# - 如何在触发时加载预制件以便我的游戏继续进行?

c# - 无法将类型 'string' 转换为 'HtmlAgilityPack.HtmlDocument'?

javascript - Jquery Validate - 无法使验证器工作

c# - 如何在Windows下的Mono上构建protobuf-csharp-port

c# - Unity 的垃圾收集器——为什么是非分代和非压缩的?

javascript - 如何在不再次发送所有 APK 的情况下更新我的应用程序?

c# - 组合框 C# 中没有显示任何内容

c# - 在 C# 中从数据库加载组合框