Skip to content

Setting null as parent using TrySetParent throws a null reference exception #2621

@powersupersport

Description

@powersupersport

Here's an example code:

public class Example : NetworkBehaviour
{
    private void Start()
    {
        Transform newParent = null; // -------------> Technically means set the parent of the object to root.
        NetworkObject.Spawn();
        NetworkObject.TrySetParent(newParent); // --------------> Throws a null reference exception.
    }
}

Here's the offending overload:

public bool TrySetParent(Transform parent, bool worldPositionStays = true)

public bool TrySetParent(Transform parent, bool worldPositionStays = true)
{
    var networkObject = parent.GetComponent<NetworkObject>();  // ----------> Why does this not check for null?

    // If the parent doesn't have a NetworkObjet then return false, otherwise continue trying to parent
    return networkObject == null ? false : TrySetParent(networkObject, worldPositionStays);
}

There is a workaround, but that's not the point. The workaround is:

public class Example : NetworkBehaviour
{
    private void Start()
    {
        Transform newParent = null;
        NetworkObject.Spawn();

        if (parent != null)
            NetworkObject.TrySetParent(newParent);
        else
            NetworkObject.TrySetParent((NetworkObject)null); // --------> The overload that accepts a NetworkObject perfectly accepts a null value.
    }
}

The reasons I consider this a bug and not a feature (of overloading methods) are two:

  • UnityEngine's transform.SetParent() perfectly accepts null as value.
  • The naming convention of putting Try in front of methods (TrySomething) means it's not supposed to throw you an exception.

Metadata

Metadata

Assignees

Labels

priority:highThis issue has high priority and we are focusing to resolve itstat:importedStatus - Issue is tracked internally at Unitytype:bugBug Report

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions