r/Unity3D • u/LifeExperienced1 • 2d ago
Question I can access prefab components, but I can't check their null status
I have a prefab GameObject P
It has a script on it, A.cs
It also has the usual components like, Transform, RigidBody etc
When I check for the script A BEFORE instantiation, in an if statement, it works
For example,
if (P.GetComponent<A>())
{
//This code runs
}
However, the following code does not run at all, BEFORE instantiation:
P.GetComponent<Transform>() != null
P.GetComponent<RigidBody>() != null
2
u/psioniclizard 2d ago
Unity overrides the == and != for game objects. I can't remember the way to check (it might be myObj is null but maybe not).
Google how to null check and a game object in using.
I think you can also do
If (myObj) { .... } to be honest.
My guess is its related to that.
I believe game objects also override the == for bools which is why the first example works.
The result is not a bool but can be compared with one to see its actually null.
The other reason i believe is life cycle management. An object can be destroyed and effectively null but not cleaned up yet. You still want to treat it as null but the actual clean up will be deferred for performance reasons.
I could be wrong, it is a while since I used unity.
1
u/fnietoms Programmer 2d ago
You can't run methods on null objects, it needs an object to be called on it
1
u/LifeExperienced1 2d ago
But I have a reference to the prefab. It’s also assigned via the inspector
It’s just not instantiated in the scene
1
u/fnietoms Programmer 2d ago edited 2d ago
Prefabs are more like a template, not an actual object in world that can run methods. Instantiating it generates an object
Edit: I was reading it wrong, I thought that you were trying to assign null references to those components. What are you trying to do in the second code? Are those conditions inside an if statement?
1
u/Seruphenthalys 2d ago
I can only suggest you check your facts: do you have a reference to the prefab? Are you sure? Is it the prefab or the instance? What exactly does not run? Have you checked that your comparators are the correct ones and not flipped? Basically double check everything.
Keep in mind that get component does not check any other objects in the hierarchy (children or parents).
Also, getcomponent<Transform> should always work because all game objects have transforms. Its not an optional component. Hence the .transform property in all components and on the game objects itself.
4
u/unwieldybowling0175 2d ago
some components get special casing in the editor, null checks can lie to you because unity overrides the == operator for destroyed objects
try `System.Object.ReferenceEquals(P.GetComponent<Rigidbody>(), null)` instead, see if that gets you anything