【问题标题】:How to access GameObject via interface如何通过接口访问 GameObject
【发布时间】:2021-09-15 04:54:45
【问题描述】:
using UnityEngine;
using System;

public interface IAimPanel
{
    public GameObject GetGameObject();
}


public class Target : MonoBehaviour, IAimPanel
{
    public GameObject GetGameObject()
    {
        return gameObject;
    }
}


public class Test : MonoBehaviour
{
    public IAimPanel aimPanel;

    private void Start()
    {
        aimPanel.GetGameObject().SetActive(true);
    }
}

我希望能够通过 Unity C# 中的接口访问 gameObject,我已经在上面的代码中完成了,但我想要一个更优雅的实现。

类似的东西

private void Start()
{
    aimPanel.gameObject.SetActive(true);
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    将您的方法更改为类和接口中的属性。

    public interface IAimPanel
    {
        GameObject GameObject { get; }
    }
    
    public class Target : MonoBehaviour, IAimPanel
    {
        public GameObject GameObject => gameObject;
    }
    

    然后你就可以按照你指定的方式访问它了:

    private void Start()
    {
        aimPanel.GameObject.SetActive(true);
    }
    

    请注意,约定是属性大写,因此我使用名称 GameObject 而不是 gameObject 来表示属性。

    【讨论】:

    • public 修饰符对接口成员无效,因为它们都是公共的 :)
    • 除了属性大写约定(我不喜欢),从Target 组件继承的gameObject 在小写gameObject 属性的情况下将被隐藏,因此任何其他名称很有道理
    • @rustyBucketBay 感谢您指出这一点,我在 .NET5 C#9 应用程序中使用 public 修饰符进行了测试,并且能够编译,但在较低版本的情况下,您是对的它会失败,所以我编辑了我的答案,谢谢!
    猜你喜欢
    • 2017-10-16
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 2019-04-17
    相关资源
    最近更新 更多