UNET add NetworkTransformChild through script

Hello there!

I am wondering can I add NetworkTransformChild component to my game object by script? I have child object that is generated for parent on the fly, when I try to do this, more specifically

var childT = this.AddComponent<NetworkTransformChild>();
childT.target = ...

the line 134(if I remember correctly) in the Awake function call in NetworkTransformChild.cs, throws NullPointException.

This is expected if NetworkTransformChild.cs use the target field in the Awake function. Despite that I intended to setup the target field on the next line after creation. Is there any workaround without implementing my own child object synchroniser? Or can I peak through how the NetworkTransformChild is implemented?

Here is the doc
http://docs.unity3d.com/Manual/class-NetworkTransformChild.html

With thanks!
Richard

I just ran into this this morning. Not sure if I’m blocked yet, but bumping this thread anyway

NullReferenceException: Object reference not set to an instance of an object
UnityEngine.Networking.NetworkTransformChild.Awake () (at C:/buildslave/unity/build/Extensions/Networking/Runtime/NetworkTranformChild.cs:135)
UnityEngine.GameObject:AddComponent()
ObjectTheory.Avatar:Start() (at Assets/ObjectTheory/Avatar/v2/Scripts/Avatar.cs:168)

This is the output immediately after creating a NetworkTransformChild in code:

NetworkTransformChild networkTransformChild = calibratedSpace.AddComponent();
networkTransformChild.target = transform;

Do you find the solution? I ran into the same problem.

The NetworkTransformChild doesn’t work, if it is created on the fly.

Yeah, I just got this issue as well, pretty sure it’s a bug. It wouldn’t have a public target property, it it was not meant to be used on runtime. Or that’s what I’m guessing.

I found a solution that worked for me.
I hope it is still usefull for you and otherwise I hope it is usefull for others that came across of this thread.

http://stackoverflow.com/questions/31359668/unity-5-1-networking-spawn-an-object-as-a-child-for-the-host-and-all-clients

There is definitely a bug in NetworkTransformChild, but I have a workaround.

The Bug:
In the awake function of NetworkTransformChild (see source), the localPosition and localPosition attributes of m_Target are being accessed even though m_Target is null. When you call AddComponent(), awake immediately starts executing, before you had a chance to set the “target” attribute.

The Workaround:
You can prevent awake from running automatically by disabling the gameobject before you add the component, and then re-enable it after you had a chance to set “target”:

this.gameObject.setActive(false);
NetworkTransformChild childT = this.gameObject.AddComponent<NetworkTransformChild>();
childT.target = ...
this.gameObject.setActive(true);
5 Likes