-
Notifications
You must be signed in to change notification settings - Fork 457
Closed
Closed
Copy link
Labels
priority:highThis issue has high priority and we are focusing to resolve itThis issue has high priority and we are focusing to resolve itstat:importedStatus - Issue is tracked internally at UnityStatus - Issue is tracked internally at Unitytype:bugBug ReportBug Report
Description
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:
com.unity.netcode.gameobjects/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs
Line 734 in 54666c3
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
'stransform.SetParent()
perfectly acceptsnull
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 itThis issue has high priority and we are focusing to resolve itstat:importedStatus - Issue is tracked internally at UnityStatus - Issue is tracked internally at Unitytype:bugBug ReportBug Report