- Home /
How to check if a specific gameobject is in the array?
I am working on a different inventory type system. What I would like it do here is be able to search the array, and if there is in fact a "Sphere" in the array, tell the user they have 1 or more Spheres. Not sure if it is possible, or maybe I should be using a list. Not sure. Any advice or tips??
here is the inventory script. I have other scripts to add items to the array already.
using UnityEngine;
using System.Collections;
public class Inventory : MonoBehaviour {
public GameObject[] items;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
void OnGUI()
{
//Insted of indexing of a specific, I want to check if any gameobject in items
//is equal to FindWithTag "Sphere". Is that possible?
if (items[0] == GameObject.FindWithTag("Sphere"))
{
GUI.Label(new Rect(100, 100, 100, 100), "You have a (or this many) sphere(s)");
}
}
}
Answer by SkaredCreations · Mar 22, 2014 at 06:36 PM
If the array list is dynamic and you can add/delete entries, then just don't use an array but a generic List (add "using System.Collections.Generic" at top of your script) and use Contains():
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Test : MonoBehaviour {
public List<GameObject> items;
void OnGUI()
{
GameObject sphere = GameObject.FindWithTag("Sphere");
if (sphere != null && items.Contains(sphere))
{
GUI.Label(new Rect(100, 100, 100, 100), "You have a (or this many) sphere(s)");
}
}
}
To add a GameObject to the list: items.Add(yourGO); To remove from the list: items.Remove(yourGO);
Your answer
Follow this Question
Related Questions
deleting a face of a proceduraly created mesh. 1 Answer
Sphere detection system 2 Answers
Creating an array of prefabs? 4 Answers
Enabled all gameobjects in array 1 Answer