Reputation: 19
I have 2 images (2 players), these will be refilled each time a player fires (working as a reload animation). Here is the code for the Reload class
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"); }
}
}
}
My problem is that even though i have the images filled in the canvas, the 'else if the images are null' check are being triggered.
Here is an image of the ReloadCanvas
Upvotes: 0
Views: 1421
Reputation: 334
The issue is that on Start() you are pointing your fillImg2 image to a null. When you use GetComponent<>() you are checking the component of a GameObject which your fillImg2 is already an image.
Remove fillImg2 = GetComponent<Image>();
from your Start method and it should no longer be null.
Upvotes: 1