- Home /
Prefab variables of disabled game objects are removed on game start.
I have two game objects InventoryCanvas and InventoryScripts. I want to be able toggle them with I press. Everything works fine if I have these objects enabled on the game start. But if they are disabled, prefabs are removed from game object that GameControl script is attached to, and I get Object reference is not set to an instance of an object error.
Would really appreciate your help. Thanks!
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameControl : MonoBehaviour {
public GameObject inventoryCanvas;
public GameObject inventoryScripts;
private bool inventoryCanvasIsOn;
private bool inventoryScriptsIsOn;
void Start () {
inventoryCanvas = GameObject.Find("InventoryCanvas");
inventoryScripts = GameObject.Find("Inventory");
}
void Update ()
{
if (Input.GetKeyDown(KeyCode.I))
{
inventoryCanvasIsOn = !inventoryCanvasIsOn;
inventoryScriptsIsOn = !inventoryScriptsIsOn;
inventoryCanvas.SetActive(inventoryCanvasIsOn);
inventoryScripts.SetActive(inventoryScriptsIsOn);
}
}
}
Answer by hamado · Jun 29, 2016 at 08:09 PM
The reference error is because the script looses connection after the game object is disabled, try disabling the canvas only instead to prevent this issue.
inventroyCanvas.GetComponent().enabled = false;
Same with the other variables you are trying to toggle.
I hope this helps, good luck!.
Already tried that. Didn't work.
But this works fine for some reason.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameControl : $$anonymous$$onoBehaviour {
public GameObject inventoryCanvas;
public GameObject inventoryScripts;
private bool inventoryCanvasIsOn;
private bool inventoryScriptsIsOn;
void Start () {
}
void Update ()
{
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.I))
{
inventoryCanvasIsOn = !inventoryCanvasIsOn;
inventoryCanvas.SetActive(inventoryCanvasIsOn);
}
if(Input.Get$$anonymous$$eyUp($$anonymous$$eyCode.I))
{
inventoryScriptsIsOn = !inventoryScriptsIsOn;
inventoryScripts.SetActive(inventoryScriptsIsOn);
}
}
}
Answer by Bunny83 · Jun 29, 2016 at 09:26 PM
The problem is that GameObject.Find can only find active gameobjects as you can read in the docs. There is no method like GameObject.Find that can find inactive GameObjects. There is Resources.FindObjectsOfTypeAll which can find inactive objects as well, but also child objects, prefabs and internal objects of Unity.
Is there a reason why you can't assign the references in the inspector at edit time?
It appears that I was trying to replace references in inspector on void start. And as you said GameObject.Find can't find inactive objects.
void Start () {
inventoryCanvas = GameObject.Find("InventoryCanvas");
inventoryScripts = GameObject.Find("Inventory");
}