- Home /
Spawning GameObject contained within another
Here is what I am trying to do. I have a gameobject. When a box collides with it, it should spawn another gameobject. I followed this link http://unity3d.com/support/documentation/Manual/Instantiating%20Prefabs.html . My code is pasted below:
var purpleTriangleBottomOuterCornerMelty : GameObject; function OnCollisionEnter(event : Collision) { Debug.Log("collision " + name); createMelty(name, transform.position); }
function createMelty(objectName: String, objectCoords: Vector3) { Debug.Log("instantiating " + meltyMappingList[objectName]["rotation"]); Instantiate(purpleTriangleBottomOuterCornerMelty, objectCoords, Quaternion.Euler(0, meltyMappingList[objectName].rotation, 0)); }
I have set the purpleTriangleBottomOuterCornerMelty variable to the prefab that I want to spawn, in the inspector of the object containing this script. But the Instantiate gives me a NullReferenceException. Apologies if I've missed something obvious, but I'm a total noob.
PS The above script is in my spawning object. I have a number of spawing objects, and want to spawn a different GameObject depending on the spawning object, so I made a mapping object (not included in the code) to map spawning object name to spawnee object.
Answer by loopyllama · Apr 29, 2011 at 07:10 AM
To me, it looks like this:
meltyMappingList[objectName]["rotation"])
and this:
meltyMappingList[objectName].rotation
are what I would concentrate on. Something isn't quite right with those two. You didn't include what the meltyMappingList is, but how can meltyMappingList[string][string] and meltyMappingList[string].rotation both be correct? Are you sure you didn't want something like:
meltyMappingList[int]+ ".rotation")
and:
meltyMappingList[int].rotation
Yeah I agree, I'm not entirely sure what's going wrong there either. objectName and "rotation" are both string keys that give values. It has a general structure like: var melty$$anonymous$$appingList = { //Top half "ltPrplTriangle1" : {"melty": "purpleTriangleTop$$anonymous$$iddle$$anonymous$$elty", "rotation" : -45}};
where "ltPrplTriangle1" is one of the expected values of objectName
But the basic problem is that it's saying that purpleTriangleBottomOuterCorner$$anonymous$$elty is null, even though I've clearly assigned it in the Inspector
with this info I can only guess. can you instaniate this prefab in another script? can you instantiate a cube in this script! can you show the entire script and paste in the error message? It is probably something simple, but not obvious from the info in the question...
Your answer
Follow this Question
Related Questions
How should i add raycast to multiple game objects??? 0 Answers
Spawn items around GameObject 3 Answers
object not spawning but no error message 2 Answers
Problem with spawn object 0 Answers