Unity中遇到以下错误:Can’t add script behaviour Interactable. The script class can’t be abstract!

我正在搭建一个射线投射的设置,让游戏物体在点击/触摸时运行代码。

if (Physics.Raycast(transform.position, transform.forward, out RaycastHit hit, maxDistance, interactableLayers))
     {
        
         if  (Input.GetButtonDown("Fire1"))
         {
             if (hit.collider != null) 
             { 

             currentInteractable = hit.collider.GetComponent<Interactable>();

             Debug.Log(hit.collider.name);

             }
         }

我跟着一个教程做的,必须使用接口来配置每个游戏对象的OnClick动作:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 // public class Interactable : MonoBehaviour 
 
 // {
 
   public interface Interactable 
   {
 
     void onClickAction(); 
 
   }

然而,我遇到了一堆错误!我无法将这个可交互脚本添加到游戏对象中,并收到以下错误提示:“Can’t add script behaviour Interactable. The script class can’t be abstract!”
我还在控制台中看到了以下信息:”Interactable is missing the class attribute ExtensionOfNativeClass!”
请问为什么会这样?

共以下 1 个回答

  • Anonymous 2023年4月6日 上午10:55


    一个接口不是一个脚本。
    接口描述了一些脚本(或更准确地说,类)应该具有的公共方法。比如下面的代码:

    
    public interface Interactible {
        void OnClickAction();
    }
    

    说明了任何实现了”Interactible”接口的脚本都应该有一个”void OnClickAction()”方法。如何实现这个方法取决于脚本本身,但当它想成为”Interactible”时,它需要有这个方法。
    好的,但是怎么样才能说某个脚本应该成为一个”Interactible”呢?像这样:

    public class SomeScript: MonoBehaviour, Interactible
    {
         public void OnClickAction() {
             Debug.Log($"OnClickAction called on { name }");
         }
    }

    非常好,但是这一切的目的是什么呢?因为这使您能够编写像这样的代码:

    Interactible currentInteractable = hit.collider.GetComponent();
    currentInteractible.OnClickAction();

    这个机制使你可以在不同类型的游戏对象上拥有许多脚本,它们都具有不同的功能,但都实现了接口“Interactible”和“OnClickAction()”方法。这样,你可以调用这些脚本中的方法,而不用管它们实际上属于哪个类。


    2 赞同 0 条回复

# 回答此问题

您的电子邮箱地址不会被公开。 必填项已用*标注