如何在 Windows App Solution side 的 Unity 脚本中检查 bool 或调用函数

How to check a bool or call a function in script of Unity on Windows App Solution side

我需要通过检查统一脚本中的布尔值来调用 Windows Store 应用端的函数。如何做到这一点我使用了这段代码,但它给出了错误。我只需要一个简单的解决方案,在其中我检查在 unity 脚本中声明的 bool 以在移植 windows store app end

调用函数
using System;
using UnityEngine;

public class SphereScript : MonoBehaviour
{
private bool m_IsMoving = true;
private bool m_IsMovingLeft = false;

public Camera GameCamera;
public event Action<bool> SphereStateChanged;
public bool IsSphereMoving { get { return m_IsMoving; } }

void Start()
{
    if (GameCamera == null)
    {
        throw new Exception("Camera is not attached to the sphere script!");
    }
}

void FixedUpdate()
{
    if (!m_IsMoving)
    {
        return;
    }

    if (m_IsMovingLeft)
    {
        transform.position -= new Vector3(0.2f, 0.0f);

        if (GameCamera.WorldToScreenPoint(transform.position).x < 100.0f)
        {
            m_IsMovingLeft = false;
        }
    }
    else
    {
        transform.position += new Vector3(0.2f, 0.0f);

        if (GameCamera.WorldToScreenPoint(transform.position).x > Screen.width - 100.0f)
        {
            m_IsMovingLeft = true;
        }
    }
}

void OnGUI()
{
    var buttonText = m_IsMoving ? "Stop sphere" : "Start sphere movement";

    if (GUI.Button(new Rect(0, 0, Screen.width, 40), buttonText))
    {
        m_IsMoving = !m_IsMoving;

        if (SphereStateChanged != null)
        {
            SphereStateChanged(m_IsMoving);
        }
    }
}
}

完整代码为here

我理解你问题的方式是,当 Unity 端发生某些事情时,你想在 Windows Store 应用程序端调用一个方法,对吗?

一个很好的方法是在您的 Unity 代码中有一个您的 Win 代码可以注册的事件。为了这个例子,我将把你的活动命名为 ButtonClicked.

首先你需要一个静态的 class 事件将在其中。在 Unity Assets 文件夹中创建一个新的 C# 脚本并将其打开。我叫我的 StaticInterop。清除生成的代码,并将其设为:

public class StaticInterop
{
  public static event EventHandler ButtonClicked;

  public static void FireButtonClicked()
  {
    if (ButtonClicked != null)
    {
      ButtonClicked(null, null);
    }
  }
}

现在,无论何时在 Unity 中发生这种情况(在本例中是单击按钮时),都执行以下代码行:

StaticInterop.FireButtonClicked();

这就是 Unity 方面的所有工作。所以创建一个构建,并打开它创建的 VS Windows Store 应用程序项目。

在 Win 代码中,您现在可以像这样报名参加活动:

StaticInterop.ButtonClicked+= StaticInterop_ButtonClicked;

并为其声明此方法 运行:

void StaticInterop_ButtonClicked(object sender, EventArgs e)
{
// Do whatever you need here.
}

需要注意的重要一点是 StaticInterop 静态 class 出现在您的 Win 代码中。这意味着您可以使用它在 Unity 和 Win 端之间传输任何内容。您甚至可以在 class 中使用一个方法调用类似 PauseGame() 的方法,然后 运行 从 Win 端使用 StaticInterop.PauseGame().