I have an Inventory : MonoBehaviour that loads some mock data in Start(), including a "selectedWeapon" variable that is set and can be read.
Let's say I want to access this variable when I set up another MonoBehaviour in the same scene.
Is there a good way to ensure that the variable is set when trying to access it? I aim to do it in Start() or some initial function preferably only once.
My temporary solution is to use the Update() function on the instance that wants to access the "selectedWeapon" from the Inventory, and repeatably tries to set it's own variable as long as it is not set.
/// This is only an example, illustrating my problem.
public class Inventory : MonoBehaviour
{
[SerializeField]
private WeaponItem m_SelectedWeapon = null;
.
.
.
void Start()
{
m_SelectedWeapon = MockDatabase.GetSelectedWeapon();
}
.
.
.
public WeaponItem GetSelectedWeapon()
{
return m_SelectedWeapon;
}
}
//--------------------------------------------------------------------
public class Actor : MonoBehaviour
{
private WeaponItem m_SelectedWeapon = null;
public Inventory inventory;
.
.
.
void Start()
{
// Would like to set up things here
// but this can let m_SelectedWeapon be null
// since it may be null in Inventory
m_SelectedWeapon = inventory.GetSelectedWeapon();
}
void Update()
{
// If not yet set, load from inventory
if(m_SelectedWeapon == null)
m_SelectedWeapon = inventory.GetSelectedWeapon();
}
.
.
.
}
The temporary solution feels unsustainable since the checks in Update will certainly grow in my project.