NullReferenceException when gamepad is disconnected - unity3d

I'm using New Input system on my game and I'm having this error
NullReferenceException: Object reference not set to an instance of an object
PauseMenu.Update ()
pointing to this line:
if (gamepad.startButton.wasPressedThisFrame || keyboard.pKey.wasPressedThisFrame)
whenever the gamepad is not connected.
void Update()
{
var gamepad = Gamepad.current;
var keyboard = Keyboard.current;
if (gamepad == null && keyboard == null)
return; // No gamepad connected.
if (gamepad.startButton.wasPressedThisFrame || keyboard.pKey.wasPressedThisFrame)
{
if (GameIsPaused)
{
Resume();
}
else
{
Pause();
}
}
}
How can I fix this?

The issue is that the exit condition requires that both keyboard and gamepad are null. In the case that gamepad is null and keyboard is not (or the other way around), an attempt is made to access a member of the null object.
You can resolve the issue by comparing each object against null before accessing its properties.
if ((gamepad != null && gamepad.startButton.wasPressedThisFrame) ||
(keyboard != null && keyboard.pKey.wasPressedThisFrame)
)
{
// Pause / Resume
}
You could also use the null conditional operator ? in each condition. When the preceding object is null, the resulting value is null. Then using the null coalescing operator ?? we convert this null value to a bool (false in this case because a null button cannot be "pressed").
if (gamepad?.startButton.wasPressedThisFrame ?? false ||
keyboard?.pKey.wasPressedThisFrame ?? false)

Related

Error: Property 'isEmpty' cannot be accessed on 'String?' because it is potentially null. Try accessing using ?. instead

I am trying to check value using if but the app crash on that line. I am using flutter.
if (value == null || value.isEmpty || !value.contains('#')) {
return 'Please enter a valid email.';
}
getting that
Error: Property 'isEmpty' cannot be accessed on 'String?' because it is potentially null.
Try accessing using ?. instead.
Please update Flutter and Dart to the latest versions. The error you describe should not happen.
This example is compiling and running perfectly fine, printing:
Please enter a valid email.
null
With no warnings or errors.
String? isValid(String? value) {
if (value == null || value.isEmpty || !value.contains('#')) {
return 'Please enter a valid email.';
}
return null;
}
void main() {
print(isValid(null));
print(isValid('valid#email.example.com'));
}
Replace
value.isEmpty
With
(value.toString()).isEmpty
Do this instead
if((value != null && (value.isEmpty() ||
!value.contains('#'))) || (value ==
null)){
}
If you have declared a variable to be nullable and did not assign a default value, and later you want to use isEmpty on that variable, you must first check that the variable is not null before checking if it's empty or not.
Adding my comment as answer so you can have better view of it:
if (value == null || ( value?.isEmpty ?? true ) || (!value?.contains('#') ?? true )) {
return 'Please enter a valid email.';
}
YOU HAVE TO REPLACE SOME OF YOUR CODE
value.isEmpty
REPLACE IT WITH
( value?.isEmpty ?? true )

Type guarding React.KeyboardEvent to reuse event handlers

I created a search-bar-React-Component that resembles the one by Google.
It should fire off a search based on the input if I either click on the 'search' icon or if I hit the enter key.
I want to reuse the same function for both the click and the keydown handler:
...
var [searchParam, setSearchParam] = useState('');
function initSearch(
e:
| React.MouseEvent<HTMLButtonElement>
| React.KeyboardEvent<HTMLInputElement>
): void {
if (e.type == 'click' || (e.type == 'keydown' && e.key == 'Enter')) {
console.log(searchParam); /* ⬆️ this throws the error */
}
}
...
TypeScript keeps giving me the following error:
'Property 'key' does not exist on type 'MouseEvent<HTMLButtonElement, MouseEvent>'
I tried both of the following:
(e instance of KeyboardEvent && e.key == 'Enter') // This is always false, since e is a React.KeyboardEvent
(e instance of React.KeyboardEvent) // KeyboardEvent is not a property of React.
What is a good way to typeguard? Is there a better way to write the function?
Thank you.
Turns out using an intersection type solved the problem:
function initSearch(
e:
| (React.MouseEvent<HTMLButtonElement> & { type: 'click' }) /*⬅️*/
| (React.KeyboardEvent<HTMLInputElement> & { type: 'keydown' }) /*⬅️*/
): void {
if (e.type == 'click' || (e.type == 'keydown' && e.key == 'Enter')) {
console.log(searchParam);
}
}
I checked the type definitions, turns out the 'type' property is only defined as 'string', not as a definite primitive value.
In case I'm missing something here (i.e. that a keydown event can somehow not include the e.type == 'keydown' property), please let me know.
It feels unnecessarily hacky!

rephrase the if statement in Dart 2.0 using null

I have following statement in flutter. weight is the text from _weightController i.e. _weightController.text
int.parse(weight).toString().isNotEmpty && int.parse(weight) > 0
But in Dart 2.0 it is not working properly. For empty TextField, it is giving the error.
====== Exception caught by gesture ==============================
The following FormatException was thrown while handling a gesture:
Invalid number (at character 1)
The code block is like this.
if (int.parse(weight).toString().isNotEmpty && int.parse(weight) > 0)
return int.parse(weight) * multiplier;
else
print('Error');
As an alternative to the other answer, you can use the tryParse() method:
Like parse except that this function returns null where a similar call to parse would throw a FormatException, and the source must still not be null.
If you use this approach, you should check the return value for null:
String weight ="";
int number = int.tryParse(weight);
if (number !=null){
print(number );
}
else
print("error");
Don't forget to also check the variable for null with weight ? "" or with weight != null
Try this:
if (weight != null && weight.isNotEmpty) {
return int.tryParse(weight) * multiplier;
} else {
print("CoolTag: error");
return -1;
}

what is dart (?. ) notation refer to?

as you maybe seen before in Effective Dart: Usage
(https://dart.dev/guides/language/effective-dart/usage)
you see :
optionalThing?.isEnabled ?? false;
I know val??other is an alternative of val == null ? other : val
but I don't understand what is ?.
The ?. operator is part of the null-aware operators. This is used in the following context:
if(object != null)
{
object.method1();
}
The above can be written as object?.method1();
So a code bool isEnabled = optionalThing?.isEnabled ?? false; will translate to following:
bool isEnabled;
if(optionalThing != null)
isEnabled = optionalThing.isEnabled;
else
isEnabled = false;
That question mark is for optionals. You can find this in swift, Kotlin and typescript as well.
Following your example optionalThing?.isEnabled is the same as:
optionalThing == null ? null : optionalThing.isEnabled;
This lets you call a method or property of an object without having to check whether the object is null. In case the object is null it would return null instead of crashing and that property or method would not be called.

coffee script testing if not defined

according to the coffee script site
console.log(s) if s?
should generate
if (typeof s !== "undefined" && s !== null) {
console.log(s);
}
But what is showing up in my browser is
if (s != null) {
return console.log(s);
}
Using coffee-script-source (1.6.2), coffee-rails (3.2.2), rails-backbone (0.7.2), rails (3.2.13)
Here is my coffee script function. any thoughts on why I am not getting what coffee script site says I should??
window.p = (s) ->
console.log(s) if s?
If you say just a bare:
console.log(s) if s?
then you will indeed get the JavaScript you're expecting (demo):
if (typeof s !== "undefined" && s !== null) {
console.log(s);
}
However, if s is a known variable such as here:
f = (s) -> console.log(s) if s?
then you'll get (demo):
if (s != null) {
//...
}
for the s? test.
So why the difference? In the first case, CoffeeScript cannot guarantee that there is an s variable in existence anywhere so it must do a typeof s check in order to avoid a ReferenceError exception.
However, if s is known to exist because it is a function parameter or has been assigned to as a local variable (so that CoffeeScript will produce a var s), then you don't need the typeof s check since you cannot, in this case, get a ReferenceError.
That leaves us with s !== null versus s != null. Dropping down to non-strict inequality (s != null) allows you to check if s is undefined or null with a single comparison. When you check typeof s !== "undefined", you wrapping the undefined test in with the "is there an s variable" check and a strict s !== null test is all that you need to check for null.
You're right,
(s) -> console.log(s) if s?
console.log(x) if x?
compiles to
(function(s) {
if (s != null) {
return console.log(s);
}
});
if (typeof x !== "undefined" && x !== null) {
console.log(x);
}
It looks like the CoffeeScript compiler is optimizing the Javascript a little bit for you, because in the case of a function argument like this, typeof s will never be undefined as s is defined right there in the function signature, even if its value is null.