玩家与物体碰撞时如何显示图像?

时间:2018-12-30 16:12:50

标签: c# image unity3d 2d-games inventory

我正在研究2D Unity游戏,我想知道当玩家与物体碰撞时如何在库存中显示图像。例如,如果播放器与鼓槌相撞,则鼓槌图像将显示在清单菜单上。

最好的问候。

Yacine TAZDAIT。

1 个答案:

答案 0 :(得分:0)

方法#1

有许多种显示图像的方法。例如,您可以拥有一个带有图像组件的图像,并在希望图像出现/消失时打开和关闭该组件。您可以使用类似于以下代码的方式进行此操作:

using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.

public class Example : MonoBehaviour
{
    public Image drumstick;

    public void Start()
    {
        toggleDrumstick(); // This will toggle the drumstick. For example, if the drumstick is not being shown at the time, the drumstick will show on the screen. The opposite is true.
    }

    public void toggleDrumstick() {
        drumstick.enabled = !drumstick.enabled;
    }
}

方法#2

上面的代码是一个很好的解决方案,但是有一种更加模块化的方式来实现它。

using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.

public class Drumstick : MonoBehaviour
{  
    public static bool enabled = this.image.enabled;
}

我推荐上述方法。这样做的原因是因为现在每个脚本都可以访问鼓槌的状态。例如,您的播放器脚本可以做到这一点。

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour
{  
    void doSomething () {
        Drumstick.enabled = true; // make the image appear.
    }
}

要使这些方法中的任何一种有效,请确保您的鼓槌使用图像组件。

编辑: 为了进一步回答您的问题,这是一种在代码中实现方法2的方法。在播放器脚本中,您可以使用OnCollisionEnter和上面的方法使鼓槌出现。

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour
{  
    void OnCollisionEnter (Collision collision)
    {
        if (collision.gameObject.tag == "drumstick") Drumstick.enabled = false;
    }
}

要使其正常工作,请确保鼓槌上带有标签"drumstick"

相关问题