- Home /
Spawn a prefab on another object based on ID?
How would I go about doing this? Are there any Tutorials or Information I can use?
Answer by maccabbe · Feb 24, 2015 at 02:08 AM
I think you are looking for switch/case or if/elseif/else statments. Not sure what you meant by spawn a prefab on another object so I assumed you wanted them to share position.
public enum ID {
Prefab1, Prefab2,
}
public class Script {
public void SpawnComponent(ID id, GameObject gameObject){
switch(id){
case ID.Prefab1: {
GameObject newObj=Object.Instantiate(Resources.Load("Prefab1")) as GameObject;
newObj.transform.position=gameObject.transform.position;
break;
}
case ID.Prefab2: {
GameObject newObj=Object.Instantiate(Resources.Load("Prefab2")) as GameObject;
newObj.transform.position=gameObject.transform.position;
break;
}
}
}
}
Im sorry but can you explain how that works? Or were you learned how to do it?
Thank you for the information!
You can learn what all this means by going though the unity tutorials at http://unity3d.com/learn/tutorials/modules/beginner/scripting. I would recommend going through all of them if you expect to be scripting.
The relevant parts in the tutorials are Beginner 27(enumeration), 2 (variables and functions), 28 (switch statements), 24(instantiate), and 13 (translate and rotate).
Afterwords learning what the tutorials offer you might still need to go through the documentation. For instance, I found how to edit the gameObject position directly at http://docs.unity3d.com/ScriptReference/Transform.htm.
Okay.. The tutorials you gave me didn't come close to matching what you put..
What is Prefab1 and 2 suppose to be anyway? The object being spawned from the object, or the spawning object?
Why do you use Resource.Load and not just connect it through the inspector?
How does it know what to compare to?
Answer by EggQuiz857 · Feb 24, 2015 at 02:35 AM
Just give the prefab the name of the id you want.
And then? If I try to spawn in multiple objects, how would the instantiated object know which ID to go to?
Your answer
![](https://koobas.hobune.stream/wayback/20220613184155im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Adding id variable # to instantiate-ed object 2 Answers
Getting instance ID from position 1 Answer
Assigning id to instantiated objects 1 Answer
Instantiate ID 2 Answers