0
\$\begingroup\$

I have a line:

private void OnTriggerEnter2D(Collider2D collider)
{
   checkID = collider.GetComponent<PartInfo>().ID;
}

That PartInfo.cs:

using System;
using UnityEngine;

public class PartInfo : MonoBehaviour
{
    [SerializeField] int id = 0;
    GameObject parent = null;

    public int ID { get { return id; } }
}

So I see this error on "checkID =" line. I don't understand why. Help me understand it, please :)

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Two possibilities: 1. compareCollider is null. 2. Component PartInfo is null, i.e., the part info was not found. Either fix the underlying or write: checkID = compareCollider?.GetComponent<PartInfo>()?.ID ?? 0; \$\endgroup\$ Commented Jun 11, 2023 at 12:46
  • \$\begingroup\$ FWIW, the function parameter is called collider and you check for compareCollider. \$\endgroup\$ Commented Jun 11, 2023 at 12:50
  • 1
    \$\begingroup\$ You'll typically want to put a breakpoint on that line and check what is wrong. \$\endgroup\$ Commented Jun 11, 2023 at 12:52

1 Answer 1

0
\$\begingroup\$

Yes, Thank you @olivier-jacot-descombes . There was no check for null. I just added

if(collider.GetComponent<PartInfo>() != null)
   checkID =...
\$\endgroup\$
2
  • \$\begingroup\$ You will have to call GetComponent twice here. Consider using pattern matching: if(collider.GetComponent<PartInfo>() is PartInfo pi) checkID = pi.ID; or an empty property pattern which also checks for "not null": if(collider.GetComponent<PartInfo>() is {} pi) checkID = pi.ID; or checkID = compareCollider.GetComponent<PartInfo>()?.ID ?? 0; to assign 0 when not part was found. \$\endgroup\$ Commented Jun 11, 2023 at 14:46
  • 2
    \$\begingroup\$ Consider using if (TryGetComponent(out PartInfo part) { checkID = part.ID; } instead. This lets you check for the existence of the component and take a reference if it exists in one concise step. It also avoids an extra allocation in edit mode (GetComponent generates a dummy object to stand in for the null for better error reporting in-editor). \$\endgroup\$ Commented Jun 11, 2023 at 16:48

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.