Is there a better way of checking if a gameObject has a component?
Am doing this:
if (previousObject.GetComponent() != null) { correctPos = previousObject.GetComponent(); }
But am getting the component twice. Is there a way to just check and have? Maybe is not that bad if I do this in awake or start, but it would be useful to know.
Hello. Answer is not 100% correct. Unamrked until its modifyed.
The first part of my answer remains valid. And I edited the second part to note that it was wrong...
Yes, but you can not mark an aswer as correct if is not 100% correct.
I see there is a comment inside the code. I changed a little the format to make it clear that part is not working in Unity :D
This is just basic program$$anonymous$$g. If you want to use an equation a few times, compute it once and put it in a variable. Suppose x can't be more than y*2+7. Ins$$anonymous$$d of writing "if(x>y*2+7) x=y*2+7" you can compute it ahead of time: int x$$anonymous$$ax=y*2+7; if(x>x$$anonymous$$ax) x=x$$anonymous$$ax;
Answer by SirPaddow · Jun 05, 2019 at 06:21 AM
Collider component = previousObject.GetComponent<Collider>();
if (component != null)
{
correctPos = component;
}
[EDITED] Removed incorrect part of the answer mentionning the "??" operator. see @Hellium comment below.
Thanks for the answer. Now am having a similar problem, and I want to know if the ?? also works. If int id != 0 { previousBaseId = id - 1;} So am doing this because the id needs to be at least 1 to get a 0 or a positive number as a result, else it should stay 0. If it´s 0 and subtracts, the id is wrong. I think this creates an error, but anyway, does the ?? work if is not posive and not just not null?
I'm not sure I understand your question, but in any case the "??" wont work with ints.
The operator ?? checks if the first value is null, but primitive types (such as int) are never null. If you try it, you will get a compiler error.
You will need the ternary operator to do what you want.
int result = (condition) ? a : b;
which can be translated as follow:
int result ;
if( condition )
result = a ;
else
result = b ;
In your case : int result = (id > 0) ? id - 1 : id ;
But more simply: if( id > 0 ) id--;
The null-coalescing operator (`??`) does not work with Unity objects as indicated in this Unity blog post because it really checks against null. However, Unity does something special with the == operator.
Thanks now am using the ternary operator. Also, I found out that the 2nd condition in an if stament is not checked if the previous was true with OR: if (id == 0 || previousObject[id - 1].transform.localScale.x >= 1)
By the way, I was using the ?? solution, and I think it didn´t gave me any errors...?
@Hellium is right, I didn't know that and didn't check it... $$anonymous$$y bad.
Now is perfect, thanks @SirPaddow
Bye :D
Your answer
![](https://koobas.hobune.stream/wayback/20220612202639im_/https://answers.unity.com/themes/thub/images/avi.jpg)