C#C
C#3y ago
henke

✅ Need help with C# unity game development.

The issue I have is that im getting reference null on this line:
itemParentObjectTransform.transform.parent = playerController.transform;
//         
//In my PlayerController : MonoBehaviour
if(Input.GetKeyDown(KeyCode.B))
        {

            GameObject[] itemObjects = GameObject.FindGameObjectsWithTag("Items");
            foreach(GameObject itemObject in itemObjects)
            {
                // Retrieve the script component attached to the child object
                ItemObject script = itemObject.GetComponentInParent<ItemObject>();
                if(script != null)
                {
                    // Call the function on the script
                    script.PickupItem();
                }
            }


//In my child of another GameObject::
public class ItemObject : MonoBehaviour
{
    public PlayerController playerController;
    public GameObject itemObject;
    public Transform itemParentObjectTransform;
 //   bool Pickable = false;
    bool isColliding = false;

    private void OnTriggerEnter2D(Collider2D collider)
    {
        if(collider.gameObject.CompareTag("Player"))
        {
            isColliding = true;
        }
    }

    private void OnTriggerExit2D(Collider2D collider)
    {
        if(collider.gameObject.CompareTag("Player"))
        {
            isColliding = false;
        }
    }

    public void PickupItem()
    {
        print("function gets called");
        if(isColliding == true)
        {
            print("works");
            // Attach the item to the player
            itemParentObjectTransform.transform.parent = playerController.transform;
            // Change the position of the item to match the player's position
            itemParentObjectTransform.transform.localPosition = Vector3.zero;
        }
        else
        {
            print("Theres no item to pickup nearby");
        }
    }

Any help appreciated!
Was this page helpful?