Hello. So recently I have been trying to make an Island Survival game. Unfortunately I cant seem to get my Wood counter to work. Here are my scripts.
1. Tree Fall Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tree : MonoBehaviour {
//Variables
GameObject thisTree;
public int treehealth = 5;
private int woodCount;
public bool isFallen = false;
void Awake()
{
}
private void Start()
{
thisTree = transform.parent.gameObject;
}
private void Update()
{
if (treehealth <= 0 && isFallen == false)
{
Rigidbody rb = thisTree.AddComponent<Rigidbody>();
rb.isKinematic = false;
rb.useGravity = true;
rb.AddForce(Vector3.forward, ForceMode.Impulse);
StartCoroutine(destroyTree());
isFallen = true;
//Counter
}
}
private IEnumerator destroyTree()
{
yield return new WaitForSeconds(10);
Destroy(thisTree);
}
}
2. Material Counter
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class MaterialCounter : MonoBehaviour {
public int woodCount = 0;
Tree healthtree;
public Text woodText;
// Use this for initialization
void Start () {
setWoodText();
}
// Update is called once per frame
void Update () {
if(healthtree.isFallen == true)
{
woodCount = woodCount + 1;
setWoodText();
}
}
void setWoodText()
{
woodText.text = "Wood: " + woodCount.ToString();
}
}
My goal for this is to get a Wood Counter at the top left showing how much “Wood” I have in my inventory. I am pretty new to Unity and C# and have been trying to learn the basics. I would love if someone can show me the right script and preferably explain it a bit on the reasoning behind it.
PS: When I run the script this is what it says. "NullReferenceException: Object reference not set to an instance of an object
MaterialCounter.Update () (at Assets/Scripts/MaterialCounter.cs:23)
"