- Home /
Find objects with tag?
Hi,
I made a ui script that instantiates a temporary guitext on an object that receives damage. This works with individual objects, but I want it so that for all gameobjects in the scene with specific tags, a guitext is instantiated above them, at their current position. How would I go about this? I attempted it but with no luck.
Here is my current script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Linq;
public class HitPoints : MonoBehaviour {
//the next position to instantiate a point prefab(at the next harmed enemy)
private Vector2 nextPosition;
//change the UI canvas transform
public Canvas prefab;
//access the UI text component
public Text text;
//how much damage to print
private int _damage;
//an array of enemies, their damage and health
private GameObject[] enemies;
private Transform[] _enemyPositions;
private Health[] _enemyHealth;
private int[] _enemyDamage;
//offset points from entity center
public Vector3 offset = new Vector3(0f, 1.5f, 0f);
void Awake () {
//get all enemies in the scene and their health and damage values
enemies = GameObject.FindGameObjectsWithTag ("Enemy");
//get the health, damage of their weapon, and position and store into array
for (int i = 0; i < enemies.Length; i++)
{
_enemyHealth[i] = enemies[i].GetComponent<Health>();
_enemyDamage[i] = enemies[i].GetComponentInChildren<EnemyAttack>().damage;
_enemyPositions[i] = enemies[i].GetComponent<Transform>();
print(enemies.Length);
}
}
void FixedUpdate () {
//as long as there are enemies, execute
if(enemies.Length > 0)
{
print ("there are " + enemies.Length + " enemies.");
//for every enemy
for(int i = 0; i < enemies.Length; i++)
{
//instantiate a point prefab for every hurt enemy
if(_enemyHealth[i].hurt)
{
nextPosition = _enemyPositions[i].position + offset;
text.text = _damage.ToString();
//print ("got this far");
Canvas hitPoint = Instantiate(prefab, nextPosition, transform.rotation) as Canvas;
}
}
}
}
//get damage from weapons
public void Damage(int dmg)
{
_damage = dmg;
}
}
Answer by fafase · Nov 26, 2014 at 07:18 AM
Instead of creating canvas above their head, I would rather add it to the prefab of the object already positioned but inactive. Then you can just show the GUI:
public void ShowUI()
{
var objects = GameObject.FindGameObjectsWithTag("Tag");
foreach(GameObject o in objects){
var comp = o.transform.Find("Canvas");
comp.gameObject.SetActive(true);
}
}
Your answer

Follow this Question
Related Questions
how to check for GameObject is null in array with random 1 Answer
(20,57): BCE0022: Cannot convert 'EnemyAI[]' to 'EnemyAI'. 1 Answer
Use an objects (from array) position to focus a camera on 3 Answers
Cannot convert 'UnityEngine.Collider[]' to 'UnityEngine.gameObject[]' using OverlapSphere 3 Answers
Detection if a GameObject is below you or next to you? 1 Answer