- Home /
Unity iOS Javascript - Problem with Instantiate
I've been on working on instantiating 10 boxes and giving them some properties. They all get the same properties for now but it i want to be able to give them different props in the future. The code worked until I put it in #pragma strict mode.. Now it says there is a Nullreferenceexeption when i ask for the obstakel.
for (var i : int = 0;i < 10; i++)
{
obstakel = Instantiate (obstakelPrefab, Vector3((i * space)+obstakelOffset, 0, 0), Quaternion.identity) as GameObject;
var tempScript:Obstakel;
tempScript = obstakel.GetComponent(Obstakel) as Obstakel;
tempScript.SetObstakel(trigger,snelheid);
}
Any ideas on what could solve my problems are very welcome!
Answer by Eric5h5 · Aug 09, 2011 at 05:32 PM
I would assume that obstaklePrefab is not of type GameObject.
By the way, in Unity 3.4 you can just write this:
var obstakelPrefab : GameObject;
function Start () {
for (var i = 0; i < 10; i++)
{
obstakel = Instantiate (obstakelPrefab, Vector3((i * space)+obstakelOffset, 0, 0), Quaternion.identity);
var tempScript = obstakel.GetComponent(Obstakel);
tempScript.SetObstakel(trigger, snelheid);
}
}
Instantiate returns the type of the prefab being instantiated (instead of Object as before), and GetComponent returns the type of the component (instead of Component as before).
Actually you can shorten it:
obstakel = Instantiate (obstakelPrefab, Vector3((i * space)+obstakelOffset, 0, 0), Quaternion.identity);
obstakel.GetComponent(Obstakel).SetObstakel(trigger, snelheid);
Or even more:
Instantiate (obstakelPrefab, Vector3((i * space)+obstakelOffset, 0, 0), Quaternion.identity).GetComponent(Obstakel).SetObstakel(trigger, snelheid);
Thank you! That last line is perfect, it doesn't solve the problem, it eli$$anonymous$$ates it.
I'm on a school macbook and updates will have to wait till school starts again but the last line works in 3.3 as well. [edit: no wait, it doesn't: getcomponent not a member of Unity.object]
$$anonymous$$oral of the story, work with up to date software.
@YvdB: You can still do it in one line on 3.3 as long as you cast appropriately:
(Instantiate (obstakelPrefab, Vector3((i * space)+obstakelOffset, 0, 0), Quaternion.identity) as GameObject).(GetComponent(Obstakel) as Obstakel).SetObstakel(trigger, snelheid);
That's maybe a bit much for one line of code though.
Your answer
![](https://koobas.hobune.stream/wayback/20220612173606im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
iTween NullReferenceException error 1 Answer
Instanciate Object Problem for Shooting 2 Answers
NullReferenceException with MoveObject.js 1 Answer
Spawn along local axis. 3 Answers