- Home /
Count the contents of the list from FindGameObjectsWithTag
I'm trying count the number of elements in the list generated by "GameObject.FindGameObjectsWithTag("soldier")" so that I can use the result to alter the addscore variable. Maybe I've been looking the places but none of the answers I've found have worked.
using UnityEngine;
using System.Collections;
public class resourceGUI : MonoBehaviour {
private float score = 0;
private float addscore;
public GameObject unit;
private GameObject tax;
void Start () {
InvokeRepeating("EachSecond", 0, 1);
}
// Update is called once per frame
void Update () {
GameObject[] tax;
tax = GameObject.FindGameObjectsWithTag("soldier");
addscore=10-tax;
}
void EachSecond(){
score=score+addscore;
}
void OnGUI(){
GUI.Box(new Rect(10,10,100,20), score.ToString());
}
}
Answer by Bunny83 · May 24, 2013 at 07:47 AM
Either use:
addscore = Mathf.Max(0, 10-tax.Length);
or
addscore = Mathf.Max(1, 10-tax.Length);
depending on whether you want addscore to be allowed to be 0 or if you want to keep it above 0
Thanks that helped a bunch, it still doesn't update every frame but it does change the addscore based on the number of gameobjects in the game. But I think a simple death trigger fix this. Thanks again.
Your answer
Follow this Question
Related Questions
setActive on object in separate scene 2 Answers
How to use FindGameObjectWithTag to get 0 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
strange behaviour when creating and deleting objects with tags 1 Answer