c# - 当玩家与物体碰撞时,我们如何显示图像?
问题描述
我正在开发 2D Unity 游戏,我想知道当玩家与物体碰撞时我们如何在我的库存中显示图像。例如,如果玩家与鼓槌碰撞,鼓槌图像会出现在物品栏菜单上。
此致。
雅辛TAZDAIT。
解决方案
方法#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"
。
推荐阅读
- c# - 用于 syslog 的 Serilog ASP.NET Core appsettings 配置
- java - 用相同的开头但不同的结尾解析java中的字符串
- typo3 - Typo3 为所有子页面创建参考元素
- amazon-s3 - BucketNotEmpty - 409 冲突不起作用
- r - 对管道中的向量进行子集化和更改
- ios - 标签不自动调整距离
- html-agility-pack - 如何使用 WebRequest 和/或 HTML Agility Pack 在 Content-Disposition 附件中获取文件
- c# - 如何用列表的内容填充 ListBox?
- c# - 应该使用什么 NpgsqlDbType 来清除“Can't write CLR type”错误
- powershell - 如何将扩展名添加到未知扩展名文件