x


MissingReferenceException?

"MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. CustomControlScript.Update () (at Assets/Scripts/CustomControlScript.cs:51)."

This is the error I'm getting when this block of code:

    if(Input.GetKeyDown(KeyCode.S))
    {
       List<GameObject> newList = new List<GameObject>();
       foreach(GameObject b in MySingleton.Instance.MyList)
       {
         AnotherScript script = (AnotherScript)b.GetComponent(typeof(AnotherScript));//Error Right Here   
         GameObject newB = script.DoSomething();
         newList.Add(newB);
       }
       foreach(GameObject b in newList)
       {
         MySingleton.Instance.MyList.Add(b);
         newList = null;
       }
    }

Is executed ONLY AFTER this block of code in MySingleton is executed (If "S" is pressed before this function is executed, all is well):

public void EmptyList()
{
       foreach(GameObject obj in MyList)
       {
         Destroy(obj);
       }
       for (int i = 0; i < MyList.Count; i++)
       {

         MyList.RemoveAt(i);
       }
}

How might I fix this issue? What I want to do is be able to clear my list whenever I want to and add new items to it afterward.

more ▼

asked May 09 '12 at 02:21 PM

Randolph_Levant gravatar image

Randolph_Levant
3 2 2 3

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

You should not empty the list with RemoveAt. Each times that function is called, the list size is decreased and i will still increase, which is going to be problematic with the loop and one element out of two won't be removed, hence the exception. Use Clear() instead.

more ▼

answered May 09 '12 at 02:56 PM

Berenger gravatar image

Berenger
11k 12 19 53

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x764
x91
x63
x30
x27

asked: May 09 '12 at 02:21 PM

Seen: 702 times

Last Updated: May 09 '12 at 02:56 PM