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.

This is just basic programming. 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 y2+7. Instead of writing "if(x>y2+7) x=y2+7" you can compute it ahead of time: int xMax=y2+7; if(x>xMax) x=xMax;

2 Answers

2

Collider component = previousObject.GetComponent();
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?

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.

@Hellium is right, I didn't know that and didn't check it... My bad.

Hello.
Answer is not 100% correct. Unamrked until its modifyed.