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

如何在类中使用任意类型类并调用其指定方法?

Hey there! Let's work through your problem—what you're looking for is exactly the kind of scenario that interfaces were made for in C# (especially in Unity, since you're using MonoBehaviour). Here's how to fix this step by step:

Step 1: Define an Interface to Set the "Contract"

First, create an interface that declares the method you want to call (next() in this case). This interface acts as a common "contract"—any class that implements this interface promises to have the next() method.

public interface IChoiceHandler
{
    // Declare the method all compatible classes must implement
    void next();
}

Step 2: Update Your Existing Class to Implement the Interface

Modify your original choiceHandler class to implement this interface. It already has the next() method, so you just need to add the interface to its definition:

public class choiceHandler : MonoBehaviour, IChoiceHandler
{
    // Your existing next() method stays exactly the same
    public void next()
    {
        // Put your original logic here (like advancing dialogue, etc.)
    }
}

Step 3: Refactor DialogueSuper to Use the Interface

Instead of declaring ch as a specific choiceHandler type, use the interface type. This lets you assign any class that implements IChoiceHandler to ch, not just your original one.

public class DialogueSuper : MonoBehaviour { 
    // Now this can hold ANY class that implements IChoiceHandler
    public IChoiceHandler ch = null; 

    void Start () { } 
    void Update () { } 

    public void end()
    { 
        // Always add a null check to avoid runtime crashes!
        if (ch != null)
        {
            ch.next(); 
        }
    } 
}

How This Solves Both Your Requirements

  1. Using any type of class: By using the IChoiceHandler interface type, you can assign any class that implements this interface to ch—whether it's your original choiceHandler, a new AdvancedChoiceHandler, or even a mock class for testing.
  2. Calling the specified method across any class: Since the interface guarantees the next() method exists, you can safely call ch.next() no matter what concrete class is assigned. Unity will handle the rest at runtime.

Bonus Tip for Unity

In the Unity Inspector, you can still drag and drop any component that implements IChoiceHandler onto the ch field—just like you did with the original choiceHandler class. No extra setup needed!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:05:27