- Home /
Does the || operator always work in UnityJS retrieval?
var go:GameObject; var goleaveblank:GameObject; private var go_assignme:GameObject;
Suppose you have three exposed game objects. Only go is assigned - say - a cube in Hierarchy.
go_assignme = goleaveblank || go; // a || default value
assuming goleaveblank=null, will the default value always be assigned, as in: `go_assignme = go;` ?
I dont think so why do you want to use || why not just assign one of them
to avoid script errors when referencing an unexpected null object, it is safer to define a default value. the above syntax works currently, but i am wondering if it works always
Answer by fafase · Nov 07, 2012 at 11:07 AM
This should not work. || is a logical operator and should only return boolean. C# would return an error. I would guess the compiler is converting go_assignement to a boolean so that you do not see any error but with C# it shows right on.
You might as well go with the ternary operator:
GameObject obj = goleaveblank ? goleaveblank:go;
If goleaveblank is null then go is return.
Note this is just a fancy way for:
GameObject obj;
if(goleaveblank)obj = goleaveblank;
else obj = go;
EDIT: Based on Izitmee comment I just add his version:
GameObject obj = goleaveblank??go;
All credits to him on that one.
I don't know if UnityScript supports this (I'm just sure Unity C# does), but since we're talking about assigning an object if it's not null, and another object if the previous one was null, this would be even more fancy ;)
GameObject obj = goleaveblank ?? go;
It's a very nice thingie: it returns the left operand if not null, and the right operand if the left one was found null http://msdn.microsoft.com/en-us/library/ms173224.aspx
But does it do what is expected? Or does it convert go_assigne into a boolean? I just think this is why some people say C# is safer than UnityScript.