- Home /
Add a Rigidbody to prefab using script
I'm trying to create a script which creates a prefab for imported assets. This prefab needs certain qualities, such as a Rigidbody. The prefab is being created, but the rigidbody is not getting added.
using UnityEngine; using UnityEditor;
public class AssetPrefabCreator : AssetPostprocessor { public void OnPostprocessModel(GameObject gameObject) { // When importing an asset with file type of FBX if (assetPath.EndsWith(".fbx")) { // Create a prefab and store the asset in it string prefabPath = assetPath.Replace(".fbx", ".prefab"); Object prefab = PrefabUtility.CreateEmptyPrefab(prefabPath);
// Adds a rigidbody
// !!! Rigidbody surrounded by sharp brackets, but doing so in text editor makes it disappear, so replaced with []'s for example. However, it has the correct brackets in the actual code.
Rigidbody gameObjectsRigidBody = gameObject.AddComponent[Rigidbody]();
EditorUtility.ReplacePrefab(gameObject, prefab, ReplacePrefabOptions.ConnectToPrefab);
EditorUtility.SetDirty(prefab);
}
}
}</pre>
What needs to be done via scripting to create a Rigidbody that is attached to the GameObject inside the newly created prefab?
Answer by Briz · Aug 02, 2012 at 03:25 PM
The problem was that the if (assetPath.EndsWith(".fbx"))
was not finding the asset based on its file type (fbx). When changed to a string that is in the asset's file name, it added the Rigidbody as instructed.
Answer by Seth-Bergman · Jul 25, 2012 at 05:35 PM
Edit: maybe try
Rigidbody gameObjectsRigidBody = prefab.gameObject.AddComponent(Rigidbody);
gotta look into this some more, now I'm just guessing :/
but I would name my argument something other than gameObject, that may confuse the compiler..
Sorry, I made a mistake in the sample code above. What you posted was actually what I already had, and isn't working. I edited the sample code to fix the mistake.
Answer by Mander · Jul 25, 2012 at 06:43 PM
u can just simply type
AddComponent(Rigidbody);
if u want to change more stuff like mass u can make a variable like this
var rigidBody : Rigidbody = AddComponent(Rigidbody);
rigidBody .mass = .5;
hope this helps
Your answer
Follow this Question
Related Questions
Enemy health. Need to take damage from two different bullet prefabs 1 Answer
is there a way to make a script prefab? 1 Answer
Tagging object while instating not working. 3 Answers
Reset script variable values automatically? 2 Answers
Shooting problem - bullet shoots diagonally when facing forward 2 Answers