0

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?

1
  • No. One for camera. and another for character controller. Commented Mar 28, 2013 at 8:46

3 Answers 3

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

2

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)

2 Comments

I understood that by remove you meant "not to add". I have edited the question to tell you how to remove.
i just want remove array key also. Then only if remove 0 th value, automatically 1st value moves to 0..
1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.