Home > front end >  How to access GameObject via interface
How to access GameObject via interface

Time:09-17

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);
    }
}

I want to be able to access gameObject via interface in Unity C#, I've done it in the code above, but I want a more elegant implementation.

Something like this

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

CodePudding user response:

Change your method into a property in the class and interface.

public interface IAimPanel
{
    GameObject GameObject { get; }
}

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

And then you'll be able to access it the way you specified:

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

Note that the convention is that properties are capitalized, so that's why I used the name GameObject instead of gameObject for the property.

  • Related