首页 > 解决方案 > Unity - 使用脚本在画布中使用填充图像的问题

问题描述

我有 2 张图片(2 个玩家),每次玩家开火时都会重新填充这些图片(作为重新加载动画)。这是 Reload 类的代码

 using System.Collections;
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;

public class Timer : MonoBehaviour {

public Image fillImg1;
public Image fillImg2;
float timeAmt = 1;
float time;

void Start() { 
   // GameObject RC = GameObject.Find("ReloadCanvas");
    fillImg2 = GetComponent<Image>();
    time = timeAmt;
}

public void Update() {

    if (Input.GetKeyDown("space"))
    {
        if (fillImg2 != null)
        {
            Debug.Log("Got to P2 Reload");
            while (time > 0)
            {
                time -= Time.deltaTime;
                fillImg2.fillAmount = time / timeAmt;
            }

            Debug.Log("Time reset - " + Time.deltaTime);
            time = timeAmt;
        }
        else { Debug.Log("Fill Image 2 is null"); }
    }

    if (Input.GetKeyDown(KeyCode.LeftShift))
    {
        if (fillImg2 != null)
        {
            Debug.Log("Got to P1 Reload");
        while (time > 0)
        {
            time -= Time.deltaTime;
            fillImg1.fillAmount = time / timeAmt;
        }

        Debug.Log("Time reset - " + Time.deltaTime);
        time = timeAmt;

    }
    else { Debug.Log("Fill Image 1 is null"); }
}
}
}

我的问题是,即使我在画布中填充了图像,也会触发“否则,如果图像为空”检查。

这是ReloadCanvas的图像

标签: c#unity3d

解决方案


问题是在 Start() 上,您将 fillImg2 图像指向空值。当您使用 GetComponent<>() 时,您正在检查您的 fillImg2 已经是图像的 GameObject 的组件。

从您的 Start 方法中删除 fillImg2 = GetComponent<Image>();,它不应再为空。


推荐阅读