You need to enable JavaScript to run this app. Unity 新手导入掷骰子脚本时遇「未继承可管理脚本的原生类」报错求助
优惠活动
大模型
产品
解决方案
定价
更多

Unity 新手导入掷骰子脚本时遇「未继承可管理脚本的原生类」报错求助

报错原因与修复方法

你遇到的「脚本未继承可管理脚本的原生类」提示,本质是代码存在多处语法错误,导致C#编译器无法完成脚本编译,Unity无法识别到合法的可挂载MonoBehaviour类,进而触发提示,具体错误与修复如下:

  • 拼写与API错误:代码中写的Random.Rango(0, 6)是错误写法,Unity提供的随机数接口为Random.Range,且该行句尾误写为冒号,应改为分号
  • 逻辑语法错误:原代码中if判断的闭合大括号位置错位,导致后续出现else id (whosTurn == -1)的错误,此处id是if的拼写错误,应调整大括号位置,补全else if的完整判断逻辑
  • 方法边界错误:原代码将whosTurn *= -1、重置coroutineAllowed的逻辑放到了RollTheDice协程方法外部,会导致大括号匹配完全错位

修复后的可正常编译的代码如下:

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

public class NewBehaviourScript : MonoBehaviour {
    
    private Sprite [] diceSides;
    private SpriteRenderer rend;
    private int whosTurn = 1;
    private bool coroutineAllowed = true;
    
    // Use this for initialization
    private void Start () {
        rend = GetComponent<SpriteRenderer>();
        diceSides = Resources.LoadAll<Sprite>("DiceSides/");
        rend.sprite = diceSides[5];
    }

    private void OnMouseDown()
    {
        if (!GameControl.gameOver && coroutineAllowed)
            StartCoroutine("RollTheDice");
    }
    
    private IEnumerator RollTheDice()
    {
        coroutineAllowed = false;
        int randomDiceSide = 0;
        for (int i = 0; i <= 20; i++)
        {
            randomDiceSide = Random.Range(0, 6);
            rend.sprite = diceSides[randomDiceSide];
            yield return new WaitForSeconds (0.05f);
        }
        GameControl.diceSideThrown = randomDiceSide + 1;
        if (whosTurn == 1)
        {
            GameControl.MovePlayer(1);
        } 
        else if (whosTurn == -1)
        {
            GameControl.MovePlayer(2);
        }
        whosTurn *= -1;
        coroutineAllowed = true;
    }
}

额外注意事项:

  • 脚本文件名必须和类名NewBehaviourScript完全一致,大小写也不能有差异,否则也会触发同类的类不合法报错
  • 修改代码后等待Unity完成编译,待控制台无红色报错后,再将脚本挂载到游戏物体上,就不会弹出原提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.28 15:06:00