Create "Optional" public variable that won't throw an error
Hello, I am trying to create a public variable of type GameObject that would be visible in the inspector but not required. With in the code I am checking for it's value and proceeding accordingly. The problem is, when the script fires (runs on trigger) It errors
nassignedReferenceException: The variable TriggerByObject of ObjectMover_Triggers has not been assigned.
I have also tried "Try" and "Catch" with no luck. So I guess the question is "How do I make a public variable optional." Any help would be much appreciated. Thanks!
[UPDATE]
I managed to work around my problem by creating a fake object then assigning it to my public Object variable at runtime if it was empty. I would still like to know if I missing something when it comes to unassigned public variables though.
Answer by UnityCoach · Aug 01, 2017 at 09:45 AM
You shouldn't have to assign fake objects.
[SerialisedField] GameObject _theObject; // keeping it private but serialised
Then, whenever you need to use it, test if it's null.
if (_theObject == null)
return; // exit method for example
Or you can even assign the default value if null in Awake
void Awake ()
{
if (_theObject == null)
_theObject = GameObject.Find("defaultObject");
}
Your answer
Follow this Question
Related Questions
Why is Unity showing the wrong variables in the Inspector? 1 Answer
Problem with the Inspector and Script 1 Answer
Health Bar Problem 1 Answer