Home > Mobile >  NullReferenceException error when trying to set localScale
NullReferenceException error when trying to set localScale

Time:07-22

I'm trying to add picking up objects feature in my FPS game. Where when the object is picked up it will be placed in an empty game object which is a child of the main camera:

enter image description here

[SerializeField] private Transform PickupParent;
void Start()
{
PickupParent = transform.parent;
}
void Update()
{
 public void PickupObject()
        {
        
        physicsObject = lookObject.GetComponentInChildren<PhysicsObjects>();
        currentlyPickedUpObject = lookObject;
        pickupRB = currentlyPickedUpObject.GetComponent<Rigidbody>();
       /* priorConstraints = pickupRB.constraints;    // <--- NEW
        pickupRB.constraints = RigidbodyConstraints.FreezeAll;    // <--- NEW*/
        pickupRB.constraints = RigidbodyConstraints.FreezeRotation;
        physicsObject.playerInteractions = this;
        pickupRB.isKinematic = true;
        pickupRB.transform.parent = PickupParent.transform;
        transform.localScale = new Vector3(1 / PickupParent.transform.localScale.x, 1 / PickupParent.transform.localScale.y, 1/ PickupParent.transform.localScale.z);

        //  StartCoroutine(physicsObject.PickUp());
    }
}

It was not working as expected as the picked-up object changes scale every time it is picked up. I tried fixing the issue by adding this line:

transform.localScale = new Vector3(1 / PickupParent.transform.localScale.x, 1 / PickupParent.transform.localScale.y, 1/ PickupParent.transform.localScale.z);

but now it is not picking up object and every time I try to pick up an object it throws this error:

NullReferenceException: Object reference not set to an instance of an object
ThePlayerInteractions.PickupObject () (at Assets/New Folder/Script/ThePlayerInteractions.cs:289)
ThePlayerInteractions.Update () (at Assets/New Folder/Script/ThePlayerInteractions.cs:147)

pointing to the same line. Why is this happening?

CodePudding user response:

This looks like your issue:

[SerializeField] private Transform PickupParent;
void Start()
{
    PickupParent = transform.parent;
}  

You're serializing PickupParent (meaning it can be set in the inspector) but then you're overwriting it in Start(). If this script is placed on a root GameObject in the scene (i.e. a GameObject with no parent), then transform.parent will be null and so will PickupParent. It seems like you should just remove the Start() function entirely and then set PickupParent in the inspector to whatever you'd like it to be.

  • Related