- Home /
AddComponent() throwing NullReferenceException
NetworkTransformChild ntc = gameObject.AddComponent<NetworkTransformChild>();
ntc.target = child.transform;
ntc.enabled = true;
I'm trying to add a NetworkTransFormChild component to my player on runtime which targets a child which is created on runtime as well. However, Unity throws me a nullreference error before the target has been set. Everything else works fine, since the second time unity goes through the script, the target has indeed been set. (with this script it gives 1 error for each child, if I comment out the target defining line it keeps on giving errors)
So my main question is: Is there a way to set the target of the component before the component is actually created? Or is there some other way around this error?
Are you doing this on Awake() function? if not try that.
I don't think I can do this on an awake function, since it needs to add the component to the parent as soon as the child is spawned, not when the parent is spawned.
Answer by Whiteleaf · Jul 23, 2016 at 03:23 PM
AddComponent is used like this:
AddComponent(typeof(NetworkTransformChild));
//I'm not sure about Unity Script, but it looks like you're using C#.
It's giving you a null error because the 'ntc' doesn't exist, that would be my best guess.
That didn't change anything, the problem is that the NetworkTransformChild requires an object reference, which I can't seem to be able to set before unity runs the script. ntc.target is the missing reference, not ntc itself. Thanks for the help though. (and yes I'm using C#)
Answer by Donderblauw · Dec 15, 2016 at 11:57 AM
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.
Your answer
Follow this Question
Related Questions
NullReferenceException - Editor script using GetComponent after AddComponent 1 Answer
NullReferenceException: Object reference not set to an instance of an object 1 Answer
Adding a component to an object over UNET? 2 Answers
Base class variables not initialized for sub class? 1 Answer
AddComponent giving NullReferenceException in Editor script 1 Answer