c# - 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"); }
}
}
}
我的问题是,即使我在画布中填充了图像,也会触发“否则,如果图像为空”检查。
解决方案
问题是在 Start() 上,您将 fillImg2 图像指向空值。当您使用 GetComponent<>() 时,您正在检查您的 fillImg2 已经是图像的 GameObject 的组件。
从您的 Start 方法中删除 fillImg2 = GetComponent<Image>();
,它不应再为空。
推荐阅读
- python-3.x - 如何为大型数据集重命名 Python Pandas 数据框中的行索引?
- php - Excel to php 删除表格和未使用的字符
- regex - 使用 XSLT 从字符串中查找动态长度数
- c# - SignalR - 启动时长时间运行的任务
- azure - 如何使用 Powershell 更改 Azure Function App 的“始终在线”?
- html - 如何检查哪些网页元素是真正可点击的?
- c# - 如何在 Code-Behind 中将 StaticRecsource 用于画笔
- java - 使用黑盒类在 Eclipse/Java 中读取 txt 文件
- python - ARIMA 模型 - MissingDataError:exog 包含 inf 或 nans
- java - 如何将分钟添加到我已经拥有的时间戳?