Mission: Junior Programming
Project: Unit 2 - Basic Gameplay
Tutorial: Bonus Features 2 - Share your Work
Hi there, I’m working my way through the different tutorials of the Junior Programming pathway. However, I’ve got stuck with the final feature from the bonus features of the second challenge, which consists of adding a health bar to all the spawning animals so that you can know how much more food you need to feed them to make them disappear.
After hours of googling I wasn’t getting anywhere near to implementing the feature, so I decided to use the step-by-step solutions pdf to be able to achieve it. Nevertheless, after following all the instructions (which you can see in the document attached below) and trying to run the game, I got the following exception:
NullReferenceException: Object reference not set to an instance of an object
DetectCollisions.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/DetectCollisions.cs:32)
The line of code causing the exception is:
other.GetComponent().FeedAnimal(1);
I have no idea why this can be happening as I haven’t worked with Unity that long. Can anyone help me?
These are the two C# files involved in this exception:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AnimalHunger : MonoBehaviour
{
// Variables
public Slider hungerSlider;
public int amountToBeFed;
private int currentFedAmount = 0;
private GameManager gameManager;
// Start is called before the first frame update
void Start()
{
hungerSlider.maxValue = amountToBeFed;
hungerSlider.value = 0;
hungerSlider.fillRect.gameObject.SetActive(false);
gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
}
// Update is called once per frame
void Update()
{
}
public void FeedAnimal(int amount)
{
currentFedAmount += amount;
hungerSlider.fillRect.gameObject.SetActive(true);
hungerSlider.value = currentFedAmount;
if(currentFedAmount >= amountToBeFed){
gameManager.AddScore(amountToBeFed);
Destroy(gameObject, 0.1f);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DetectCollisions : MonoBehaviour
{
// Variables
private GameManager gameManager;
// Start is called before the first frame update
void Start()
{
gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
}
// Update is called once per frame
void Update()
{
}
// Destroy objects on collision event
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player")){
gameManager.RestLives(1);
Destroy(gameObject);
}
else {
//gameManager.AddScore(1);
//Destroy(other.gameObject);
other.GetComponent<AnimalHunger>().FeedAnimal(1);
Destroy(gameObject);
}
}
}
8189286–1067313–Unit 2 - Bonus Features Solutions.pdf (3.42 MB)