You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity挂载Answer脚本报未继承可管理原生类错误求助

故障根因

脚本无法挂载的报错由代码中的多处语法错误、类型引用错误、命名不匹配问题引发,部分隐性错误不会立刻触发编译弹窗,但会阻止Unity正确识别脚本为可挂载的MonoBehaviour类型,具体问题如下:

  • Answers.cs 错误点
    1. 继承MonoBehaviour的类不允许声明和类名同名的自定义构造方法,代码中public void Answers()属于违规写法,会直接导致Unity判定该脚本不可用
    2. Debug.log大小写错误,正确写法为Debug.Log
    3. if分支花括号未闭合,if块结束后缺少右花括号
  • Quizmanager.cs 错误点
    1. 未引用UnityEngine.UI命名空间,无法识别Text类型
    2. QnA.RemoveAt[currentquestions]写法错误,RemoveAt是方法,需使用小括号:QnA.RemoveAt(currentquestions)
    3. for循环语法错误:关键字错写为inr、循环变量错写为数字1、迭代器错写为int++,正确写法为for(int i=0; i < options.Length; i++)
    4. 脚本引用名不匹配:实际答案类名为Answers,但代码中先后出现AnswersScript、AnswerScript两种不存在的类名
    5. 缺失Questions类定义,代码中使用了List<Questions>但未实现该类,也会引发编译异常

修复代码

修复后的Answers.cs

using UnityEngine;

public class Answers : MonoBehaviour
{
    public bool isCorrect = false;
    public Quizmanager quizmanager;

    // 原构造方法重命名为OnAnswerSelect,可绑定到按钮点击事件
    public void OnAnswerSelect()
    {
        if (isCorrect)
        {
            Debug.Log("Correct answer!");
            quizmanager.correct();
        }
        else
        {
            Debug.Log("Wrong answer ~");
        }
    }
}

修复后的Quizmanager.cs

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

public class Quizmanager : MonoBehaviour
{
    public List<Questions> QnA;
    public GameObject[] options;
    public int currentquestions;

    public Text Questiontxt;

    private void Start()
    {
        generatequestion();
    }

    public void correct()
    {
        QnA.RemoveAt(currentquestions);
        generatequestion();
    }

    void Setanswers()
    {
        for(int i=0; i < options.Length; i++)
        {
            options[i].GetComponent<Answers>().isCorrect = false;
            options[i].transform.GetChild(0).GetComponent<Text>().text = QnA[currentquestions].Answers[i];
            if(QnA[currentquestions].CorrectAnswer == i + 1)
            {
                options[i].GetComponent<Answers>().isCorrect = true;
            }
        }
    }

    void generatequestion()
    {
        currentquestions = Random.Range(0, QnA.Count);
        Questiontxt.text = QnA[currentquestions].Question;
        Setanswers();
    }
}

补充Questions类实现

需要单独新建一个Questions.cs文件,或者直接写在Quizmanager.cs的末尾,内容如下:

[System.Serializable]
public class Questions
{
    public string Question;
    public string[] Answers;
    public int CorrectAnswer;
}

后续操作

代码修改完成后,点击Unity顶部菜单Assets > Refresh刷新资源,编译完成后即可正常挂载Answers脚本到按钮组件上。


内容的提问来源于stack exchange,提问作者Rikuo_Otonashi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 00:09:01