简体   繁体   English

以编程方式在运行时更改Unity Sprite

[英]Change Unity Sprite during run time programmatically

I'm new to Unity so this seems like a very basic question but I've been working on it for a while and google and Unity Docs hasn't helped much so: 我是Unity新手,所以这似乎是一个非常基本的问题,但是我已经进行了一段时间了,而Google和Unity Docs并没有太大帮助:

I want to change the Health sprite shown here: 我想更改此处显示的“健康”精灵:

在此处输入图片说明

When my LoseCollider at the bottom of the screen gets triggered. 屏幕底部的我的LoseCollider被触发时。 The sprite would change to a 2 health and a 1 health sprite: 该精灵将变为2健康和1健康精灵:

在此处输入图片说明

In code I'd like to have: 在代码中,我想拥有:

if (health == 3) {
 // Switch to 3 hearts sprite.
 }
 else if (health == 2) {
 // Switch to 2 hearts sprite.
 }
 else if (health == 1) {
 // Switch to 1 heart sprite.
 }

Based on my current code: 根据我当前的代码:

在此处输入图片说明

在此处输入图片说明

How can I change my Sprites? 如何更改我的Sprites?

在此处输入图片说明

Hmm, I think I saw the problem. 嗯,我想我看到了问题。 Use this code instead: 请改用以下代码:

    HealthManager hManager;
void OnTriggerEnter2D (Collider2D trigger)
{
    if (hManager.totalHealth >= 3)
    {
        hManager.LoadHealthSprites();
        hManager.totalHealth--;
    }
    else
    {
        levelManager = GameObject.FindObjectOfType<LevelManager>();
        levelManager.LoadLevel("Lose");
    }
}

void Start()
{
    hManager = hpManager.GetComponent<HealthManager>();
}
if(HealthManager.totalHealth>=3) 
{

}

I think there is an logical error. 我认为这是一个逻辑错误。 it will never call LoadHealthSprite func if totalHealth is smaller than 3. Change this part as: 如果totalHealth小于3,它将永远不会调用LoadHealthSprite函数。将此部分更改为:

if(HealthManager.totalHealth>0)
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM