Sona Rijesh
Sona Rijesh

Reputation: 1035

Check a value exist in array in unity 3d

I have two script.

Script1 Script2

In Script1 i declared a arraylist it contains value 2, 4, 6, etc...

public static ArrayList aArray= new ArrayList();

function update(){
   if(bool1)
   {
      aArray.Add(i);
   }
}

I have to check a value 5 exist in arraylist from Script2.

if value exists i have to get its key.

How to get it?

Upvotes: 0

Views: 14821

Answers (3)

Oscar Foley
Oscar Foley

Reputation: 7025

Try using Contains. This code will detect if you have already the value in the ArrayList and will stop code from adding it a second time.

public static ArrayList aArray= new ArrayList();

function update()
{
   if(aArray.Contains(i)==false)
   {
      aArray.Add(i);
   }
}

If you want to remove a value it is just as easy as aArray.Remove(i)

Upvotes: 2

Steven Mills
Steven Mills

Reputation: 2381

if I understood correctly, Script1 is in your camera, and Script2 is in a Character. For the sake of this example we'll call them MainCamera and Character respectively.

Now, unless I understood wrong, you're trying to access an Array in Script1 from Script2. While the other answers are very much correct, unity3D has a bit of a workaround needed to access it.

Anyway, within Script2 use this:

if(GameObject.Find("MainCamera").GetComponent<Script1>().aArray.Contains(5))
{
   //Do your code here
}

Upvotes: 1

Botz3000
Botz3000

Reputation: 39610

First, i would recommand using a generic List<T> instead of the non-generic ArrayList, which enables you to specify the type of objects that go into that list (for better type safety).
Also, declaring a variable readonly prevents you from accidently overwriting it, which is often the case with Lists (after all, you can always just Clear them):

public static readonly List<int> items = new List<int>();

Now to answer your actual question, if you want to check if a value exists in the list, you can use the method Contains.
To check if the value does not exist, just put an ! in front of the expression:

if (!Script1.items.Contains(i)) {
    // This will only execute if the list does not contain i.
    items.Add(i);
}

Upvotes: 3

Related Questions