【问题标题】:error CS0117: 'Level' does not contain a definition for 'Instance'错误 CS0117:“级别”不包含“实例”的定义
【发布时间】:2019-08-12 07:40:22
【问题描述】:

我是 C# 的新手。想开发游戏。 Unity 更改了一些语法,例如 Application.无法解决错误。检查所有拼写。实例如何在这里工作。

尝试在 Unity 文档和谷歌中搜索。它来自我正在学习的书。可在谷歌中找到。如果我们键入它给出的代码。

块引用

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using RunAndJump;
 using UnityEditor;

    [ExecuteInEditMode] public class SnapToGridTest : MonoBehaviour {
 // Update is called once per frame
    private void Update()
     {
         Vector3 gridCoord = 
              Level.Instance.WorldToGridCoordinates(transform.position);
         transform.position = 
              Level.Instance.GridToWorldCoordinates((int)gridCoord.x,
         (int)gridCoord.y);
     }

     private void OnDrawGizmos()
     {
         Color oldColor = Gizmos.color;
         Gizmos.color = (Level.Instance.IsInsideGridBounds(transform.position)) 
                         ? Color.green
                                     : Color.red;
         Gizmos.DrawCube (transform.position, Vector3.one * Level.GridSize);
         Gizmos.color = oldColor;
     } }

块引用

错误 CS0117:“级别”不包含“实例”的定义

【问题讨论】:

  • 很难说没有看到Level 的代码,但正如错误状态...没有定义Instance .. 也许你或这本书缺少一些东西;)
  • 我对你的库没有深入了解,但是如果你使用 Visual Studio 或一些 IDE,如果你只是写 Level 然后写一个 .,IDE 应该会建议你在哪里可以找到您正在寻找的方法。
  • 你可以为Level展示你的脚本吗?
  • @madhans 您提供的链接是partial class 所以.. 它的其余部分在哪里?在您链接的部分中,至少没有Instance nowhere

标签: c# unity3d


【解决方案1】:

您似乎正在尝试将 Level 视为 Singleton,但尚未实现 Level 的单例。

你可以这样实现一个单例:

private static Level instance;

public static Level Instance 
{
    get 
    {
        if (instance == null)
        {
            instance = FindObjectOfType<Level>();
        }

        return instance
     }
}

当然,如果当前场景中没有附加Level 组件的GameObject,它将无法工作。

此外,您目前正在遵循的教程书似乎已将 Level 作为部分类。
该指南可能为包含 Singleton 的部分 Level 类制作了另一个脚本。
您可能只是错过了它,或者指南尚未进入该部分。

【讨论】:

  • 只需要添加,因为 FindObjectOfType 方法很慢,你应该使用方法而不是属性。因为属性通常意味着它们的实现是快速和可靠的。
猜你喜欢
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-17
  • 2011-02-18
  • 1970-01-01
  • 2018-09-29
  • 2019-11-02
相关资源
最近更新 更多