【问题标题】:Unity - Error CS106: Type 'Score' does not contain a definition for scoreUpUnity - 错误 CS106:类型“分数”不包含 scoreUp 的定义
【发布时间】:2021-10-23 17:19:35
【问题描述】:

在过去的几天里,我一直在尝试制作一个简单的飞鸟游戏。目前,我正在尝试编写一些代码,让玩家每次通过两个管道时得分都会上升。不过我遇到了一个错误,我不太确定如何解决它。这是我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Score : MonoBehaviour {

    public static int score = 0;

    private void Start() {
        score = 0;
    }

    private void Update() {
        GetComponent<UnityEngine.UI.Text>().text = score.ToString();
    }

    public void scoreUp() {
        score++;
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class AddScore : MonoBehaviour {

    public Score score;
    
    private void OnTriggerEnter2D (Collider2D collision) {
        score.scoreUp(); // the line thats giving me problems
    }

}

我得到的错误是:error CS1061: Type Score does not contain a definition for scoreUp and no extension method scoreUp of type Score 可以找到。

这对我来说没有意义。 Unity 说“当您尝试调用方法或访问不存在的类成员时会导致 CS1061 错误。”。但是从上面的代码中可以看出,我确实有一个名为 Score 的类,并且我在其中有一个名为 scoreUp() 的方法。

此外,我之前使用过这种代码(我创建了一个类,在另一个类中使用它及其方法)没有任何问题。所以我真的不确定这个特定场景中的问题是什么。

【问题讨论】:

  • 当您输入score. 时,您的编辑器应该会显示可用的方法。它是否显示scoreUp?也许还有另一个名为 Score 的类具有绝对另一种功能(也许它是来自您的一些外部资产的类)
  • 我建议您缓存分数 UI 对象,而不是每次在更新函数中查找它。为此,请定义 Start 方法,然后获取它并将其保存在本地。 var scoreText = GetComponent&lt;UnityEngine.UI.Text&gt;();
  • 请使用正确的标签!请注意,unityscript 是或更好的是曾经是一种 JavaScript 风格,类似于早期 Unity 版本中使用的自定义语言,并且现在已经不推荐使用了!您的代码显然是 c# ...您应该使用 unity3d 这是您在这里使用的主要框架/API
  • 您确定它引用了正确的Score 类型吗?你有多个程序集/命名空间等吗?你确定某处没有错字吗?

标签: c# unity3d


【解决方案1】:

我认为解决您的问题的方法是让“AddScore”类成为“Score”的子类。

要让它成为一个孩子,只需改变 AddScore : MonoBehaviour -> AddScore : 分数

除了使用 public scoreUp() 之外,您还可以做什么将其设为 Protected,以便只有子类可以访问它。

你的代码应该是这样的

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Score : MonoBehaviour {

    public static int score = 0;

    private void Start() {
        score = 0;
    }

    private void Update() {
        GetComponent<UnityEngine.UI.Text>().text = score.ToString();
    }

    protected void scoreUp() {
        score++;
    }

第一位和第二位

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class AddScore : Score{

    private void OnTriggerEnter2D (Collider2D collision) {
        scoreUp();
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多