unity3d 从Unity中的另一个名称空间访问公共方法

7eumitmz  于 2022-11-16  发布在  其他
关注(0)|答案(1)|浏览(233)

我正在尝试访问ARCoreBackgroundRenderer类中的一个公共方法,这个类是MonoBehavior,位于GoogleARCore命名空间中,在另一个类中,这个类也是MonoBehavior,名为UIController,位于另一个名为CompanyController的命名空间中。这可能吗?我该怎么做?
我在第二个类中尝试调用的方法是:

public void DisableARBackgroundRendering()
    {
        if (m_CommandBuffer == null || m_Camera == null)
        {
            return;
        }

        m_Camera.clearFlags = m_CameraClearFlags;

        .......

    }

我想在我的第二个类中用一个简单的方法调用这个方法。

nimxete2

nimxete21#

通常,参考相应的API会有所帮助
ARCoreBackgroundRendererAPI Reference)就像你说的那样是一个,在命名空间GoogleARCore中..所以通过

using GoogleARCore;

或使用

GoogleARCore.ARCoreBackgroundRenderer

UIController中输入代码。

using UnityEngine;
using GoogleARCore;

namespace CompanyController
{
    public class UIController : MonoBehaviour
    {
        // Reference this via the Inspector by drag and drop 
        // [SerializeField] simply allows to serialize also private fields in Unity
        [SerializeField] private ARCoreBackgroundRenderer arRenderer;

        // Alternatively you could as said use the type like
        //[SerializeField] private GoogleARCore.ARCoreBackgroundRenderer arRenderer;

        private void Awake ()
        {
            // As a fallback find it on the scene
            if(!arRenderer) arRenderer = FindObjectOfType<ARCoreBackgroundRenderer>();
        }

        public void DisableARBackgroundRendering()
        {
            // Now use any public method of the arRenderer 
            arRenderer.SomePublicMethod();
        }
    }
}

但是,你也可以看到方法DisableARBackgroundRenderingprivate,你将无法使用它。同样,m_Cameram_CommandBuffer都是private,所以你将无法访问它们。
可以并且-如果您仔细研究ARBackgroundRenderer的实现-希望在这里做的只是启用和禁用相应的组件:

public void EnableARBackgroundRendering(bool enable)
{
    arRenderer.enabled = enable;
}

因为在内部,它会自己处理其余的事务,您不需要进一步访问它的方法、字段和属性:

private void OnEnable()
{
    if (BackgroundMaterial == null)
    {
        Debug.LogError("ArCameraBackground:: No material assigned.");
        return;
    }

    LifecycleManager.Instance.OnSessionSetEnabled += _OnSessionSetEnabled;

    m_Camera = GetComponent<Camera>();

    m_TransitionImageTexture = Resources.Load<Texture2D>("ViewInARIcon");
    BackgroundMaterial.SetTexture("_TransitionIconTex", m_TransitionImageTexture);

    EnableARBackgroundRendering(); // AS YOU SEE IT ALREADY CALLS THIS ANYWAY
}

private void OnDisable()
{
    LifecycleManager.Instance.OnSessionSetEnabled -= _OnSessionSetEnabled;
    m_TransitionState = BackgroundTransitionState.BlackScreen;
    m_CurrentStateElapsed = 0.0f;

    m_Camera.ResetProjectionMatrix();

    DisableARBackgroundRendering(); // AS YOU SEE IT ALREADY CALLS THIS ANYWAY
}

相关问题