Turn "on" and "off" objects error.

I need to turn on and off object by Input.GetKey"…"

When I press “1” object is working, no error

When I press “2” object disables, no error

When I press “1” again, object doesn’t turn “on” and I see an error “Object reference not set up to an instance of an object” on the “SetActive(true);” line

The script is inside “Character” gameobject.
20596-desword.jpg

void Update () 
{ 		
   if(Input.GetKeyDown("1"))
      GameObject.Find("Sword").SetActive(true);
   else if (Input.GetKeyDown("2"))
      GameObject.Find("Sword").SetActive(false);
}

I think that’s because it cannot find “Sword” I think it only searches the active tags, …

Try making the reference to the object before you disable it.

like:

GameObject GO;
void Start(){
    GO = GameObject.Find("Sword");
}
void Update (){
    if(Input.GetKeyDown("1"))
        GO.SetActive(true);
    else if (Input.GetKeyDown("2"))
        GO.SetActive(false);
    }