【问题标题】:How can we display an image when the player collide with an object?当玩家与物体碰撞时,我们如何显示图像?
【发布时间】:2018-12-30 16:12:49
【问题描述】:

我正在开发 2D Unity 游戏,我想知道当玩家与物体发生碰撞时,我们如何在我的库存中显示图像。例如,如果玩家与鼓槌碰撞,鼓槌图像会出现在物品栏菜单上。

最好的问候。

雅辛·塔兹代特。

【问题讨论】:

  • 请参观并阅读指南。就像现在一样,你的问题太宽泛了。也可以尝试事先研究和咨询教程

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


【解决方案1】:

方法#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"

【讨论】:

    猜你喜欢
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多