- Home /
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.
Answer by Berenger · May 09, 2012 at 02:56 PM
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.
Your answer
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Remove and Destroy Instantiated object in list 1 Answer
Remove dead enemies from array 1 Answer
Checking to see if there are no more of a certain object in the scene? 1 Answer
Weird issue with List and for loop. 1 Answer