Custom class, Null Reference Exception
I've created a custom class but for some reason it throws a null exception when I try to run the code that was otherwise fine. The problem is on the line with _renderer[clone]
statement.
private Machine[] _machineClone;
void Start()
{
// Set machines and properties array
_machineClone = new Machine[machineCount];
...
// Spawn machine
_machineClone[count] = Instantiate(machine, pos, Quaternion.identity) as Machine;
// Get machine renderer to use later
_renderer[count] = _machineClone[count].gameObject.GetComponent<Renderer>() as Renderer;
...
public class Machine : MonoBehaviour
{
public GameObject gameObject;
}
Answer by $$anonymous$$ · Jul 21, 2016 at 01:56 PM
So what cured this is I had to change my clone assignment line to
_machineClone[count] = ((GameObject)Instantiate(machine, pos, Quaternion.identity)).GetComponent<Machine>();
as pointed out by @M-Hanssen and then move my Machine class to a separate script and attach it to the prefab and set the GameObject.
Answer by M-Hanssen · Jul 21, 2016 at 08:07 AM
Change your line to this:
_machineClone[count] = ((GameObject)Instantiate(machine, pos, Quaternion.identity)).GetComponent<Machine>();
This line still throws a null exception
_renderer[count] = _machineClone[count].gameObject.GetComponent<Renderer>() as Renderer;
Answer by rmassanet · Jul 20, 2016 at 02:36 PM
Instantiate
returns a reference to the GameObject just instantiated, but you are casting it to your Machine script, which is not a GameObject and probably causes the null
value you are observing.
That's seems likely. Ins$$anonymous$$d of "as $$anonymous$$achine;" do ".GetComponent();"
That doesn't compile. 'Object does not contain a definition for 'GetComponent'.'
Cast it to GameObject
and then call GetComponent
.
Answer by JamesLawrenceMyQVO · Jul 20, 2016 at 02:18 PM
I'm guessing it is throwing the exception on the line with the GetComponent()? It is hard to tell what might be causing it with the limited look at the code, since I'm not sure how things are instantiated, but could it be an off by one error with count vs machineCount? _machineClone would be indexed from 0 up to machineCount - 1, but maybe your count is going all the way up to machineCount?
Yeah, that's the line. The count is fine, it worked before I introduced the custom $$anonymous$$achine class.