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

Unity中如何访问实现特定接口的GameObject类的已实现属性

问题:通过接口访问GameObject上不同类的统一属性

我想访问GameObject上实现了特定接口的类的属性变量,这些类名称不同,但都实现了同一个接口,希望通过接口来访问定义的变量。我写了如下脚本:

SampleClass.cs

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

public class SampleClass : MonoBehaviour, ISampleInterface
{
    public int sampleVariable 
    { 
        get => throw new System.NotImplementedException(); 
        set => throw new System.NotImplementedException(); 
    }
}

ISampleInterface.cs

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

interface ISampleInterface
{
    public int sampleVariable { get; set; }
}

层级视图说明

多个GameObject对象,每个对象挂载了不同名称但实现了ISampleInterface接口的MonoBehaviour脚本。

目标逻辑(当前无法运行)

sampleObject.GetComponent<ISampleInterface>().sampleVariable = ~~~

解决方案

Unity默认的泛型GetComponent<T>()不支持直接传入接口类型,以下两种方法可以解决这个问题:

方法1:遍历组件筛选接口实例

获取GameObject上所有MonoBehaviour组件,筛选出实现目标接口的对象:

var interfaceComp = sampleObject.GetComponents<MonoBehaviour>()
    .OfType<ISampleInterface>()
    .FirstOrDefault();

if (interfaceComp != null)
{
    interfaceComp.sampleVariable = 10; // 示例赋值
}

方法2:通过Type类型获取并转换

使用GetComponent(Type)方法传入接口类型,再强制转换为目标接口:

var interfaceComp = sampleObject.GetComponent(typeof(ISampleInterface)) as ISampleInterface;

if (interfaceComp != null)
{
    interfaceComp.sampleVariable = 10; // 示例赋值
}

补充:完善接口属性实现

你当前的SampleClass中属性仅抛出异常,需要替换为实际的实现逻辑,比如绑定私有字段:

public class SampleClass : MonoBehaviour, ISampleInterface
{
    [SerializeField]
    private int _sampleVar;

    public int sampleVariable 
    { 
        get => _sampleVar; 
        set => _sampleVar = value; 
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 11:45:16