public class CreateObject : MonoBehaviour
{
[MenuItem(“Object Creator/Create Object”)]
static void DoSomething()
{
var g = new GameObject(“Object 1”);
var g2 = new GameObject(“Object 2”);
var k = g.AddComponent(); //k == null
var l = g2.AddComponent(); // l == null
var d = g.GetComponent(); //d == null
d.Test.Add(new Test{ Name = “Test” });
var p = g2.GetComponent(); //p == null
p.Name = “Test”;
}
}
When I add a component to a gameobject it returns null.
And when I try to get the component it also returns null…
Why does this happen?
Edit:
I have this version of unity:
Version 4.3.4f1 (e444f76e01cd)
Thu, 23 Jan 2014 00:16:56 GMT
And the gameobjects get instantiated, and the components get added
For me, AddComponent was returning null because I was trying to attach an abstract class. Here’s log message that was logged after the null pointer error I was getting:
Cannot add component of type ‘Joint’
because it is abstract. Add component
of type that is derived from ‘Joint’
instead.
So I changed Joint to ConfigurableJoint and it worked.