2
\$\begingroup\$

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. grid.objGridSize () (at Assets/scripts/grid.cs:119) grid.hit (System.String hitObjString) (at Assets/scripts/grid.cs:109) grid.Update () (at Assets/scripts/grid.cs:80)

I'm getting this error and strange results after finding a gameobject, storing it in a new GameObject variable and then destroying it:

void Update () {
    if(Input.GetButtonDown("Fire1")){ // detect left mouse click

        ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        Debug.Log("clicked");

        if(Physics.Raycast(ray, out hitObj)){
            if(hitObj.collider != null){

                // send a message to the object that got hit
                hit(hitObj.collider.gameObject.name);
            }
        }
    }
}
public void hit(String hitObjString){

    Debug.Log("I got hit: "+name);

    GameObject hitTile = GameObject.Find(hitObjString);

    if( hitTile.tag == "tile"){

        Destroy(hitTile);
    }
}
\$\endgroup\$
  • \$\begingroup\$ what is the code at line 119? i'm guessing its missing here judging by the filenames and line numbers missing, and that you have another custom function 'objGridSize' in there that would be useful to see in order to answer this meaningfully. \$\endgroup\$ – jheriko Nov 8 '15 at 15:22
4
\$\begingroup\$

Passing through the gameObject name to a method, then using GameObject.Find to find it again by its name, is bad practice, and inefficient.

GameObject.Find is an expensive operation.

Rather do something like this...

    void Update () {
    if(Input.GetButtonDown("Fire1")){ // detect left mouse click

        ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        Debug.Log("clicked");

        if(Physics.Raycast(ray, out hitObj)){
            if(hitObj.collider != null){
                hit(hitObj);
            }
        }
    }
}
public void hit(GameObject hitObj){

    Debug.Log("I got hit: "+ hitObj.name);

    if( hitObj.tag == "tile"){

        Destroy(hitObj);
    }
}
\$\endgroup\$
  • \$\begingroup\$ Thanks!! Started working, after doing the above but changing the hit(hitObj) to hit(hitObj.transform.gameObject) \$\endgroup\$ – benbyford Nov 21 '15 at 22:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.