Hi Everyone,
I’m new on here and also quite new to c# and Unity. Please be gentle with me if I’m asking a dumb question.
I was hoping for some help on something that is doing my head in. I am instantiating 2000 prefabs and have them rotate and move around the screen randomly. I have actually got the code working fine if I declare the prefab as global and drop the actual prefab onto the navigator window.
However this means it is always the same prefab floating about, but I want to put some different ones up into the air. I have created an array of prefabs and I am trying to assign one of the 22 different elements, randomly, to the instantiation. This is where the code falls down.
It is the line:
GameObject fragment = (GameObject) Instantiate(fragmentloadarray[iValue], position, Quaternion.Euler
that is causing the error: “NullReferenceException: Object reference to set to an instance of an object”
void Start()
{
fragmentloadarray = new GameObject[22];
fragmentloadarray = Resources.LoadAll("Fragments") as GameObject[];
fragmentarray = new GameObject[numberOfFragments];
for (int count = 0; count < numberOfFragments; count++)
{
Vector3 position = new Vector3(Random.Range(-sizeofarea, sizeofarea), Random.Range((-sizeofarea + 1.9f) / 1.4f, (sizeofarea + 1.9f) / 1.4f), Random.Range(-sizeofarea + 0.8f, sizeofarea + 0.8f));
iValue = Mathf.RoundToInt(Random.Range(0.0f, 21.0f));
GameObject fragment = (GameObject) Instantiate(fragmentloadarray[iValue], position, Quaternion.Euler
(
Random.Range(0.0f, 360.0f),
Random.Range(0.0f, 360.0f),
Random.Range(0.0f, 360.0f)
));
fragmentarray[count] = fragment;
fragment.GetComponent<Rigidbody>().AddTorque(transform.up * Random.Range(-spinrate, spinrate));
fragment.GetComponent<Rigidbody>().AddTorque(transform.right * Random.Range(-spinrate, spinrate));
float scalefactortoapply = Random.Range(0.05f, 0.65f);
Vector3 scale = fragment.transform.localScale;
scale.Set(scalefactortoapply, scalefactortoapply, 0.1f);
fragment.transform.localScale = scale;
fragment.GetComponent<Rigidbody>().AddForce
(
Random.Range(-fragmentspeed, fragmentspeed),
Random.Range(-fragmentspeed, fragmentspeed),
Random.Range(-fragmentspeed, fragmentspeed)
);
}
}
I have been stuck on this for a few days now and would really appreciate some advice from the pro’s
Thanks in advance
Ian

