x


how to aply diferent fbx models to prefab at runtime

I have created one prefab of cube which is moving in one direction. now I want to apply Different characters to prefab at run time. I want different animals with some animation like walking in one side are to be generated with each instantiation of a cube prefab. So how to do it? can anyone help me with detail description and code

more ▼

asked Apr 02 '12 at 08:10 AM

RachelD gravatar image

RachelD
16 7 14 17

You can't modify prefabs at runtime. Just instantiate different prefabs, or have a single prefab with references to several mesh/material pairs.

Apr 02 '12 at 08:13 AM syclamoth
(comments are locked)
10|3000 characters needed characters left

1 answer: sort oldest

I have found it very useful to set up systems to do exactly what you are asking. By keeping the model separate from the prefab that represents game logic for an entity, you can apply that logic to any number of different models without duplicating that logic in a prefab for each model. You also gain the benefit of maintenance free model importing. If you change the fbx, there's no need to recopy it to another prefab as the dyanmic attaching of the model will always use the the most current model.

Here is a simple example of how to get started with such a system. Attach this class to the prefab you want models to be attached to. Then, assign your potential models to the ModelPrefab array in the Inspector. The example chooses models randomly, but you could write a more specific selection method if you need to.

public class PrefabShell : Monobehaviour {
    // Model that you can set on the prefab in the inspector, or via another script
    public GameObject[] ModelPrefab;

    public void AttachModelToPrefab(GameObject modelPrefab) {
       // Create an instance of the desired model
       GameObject modelInstance = GameObject.Instantiate(modelPrefab) as GameObject;

       // The prefab shell should determine the model transform
       modelInstance.transform.position = transform.position;
       modelInstance.transform.rotation = transform.rotation;

       // Attach the model instance to the prefab shell
       modelInstance.transform.parent = gameObject.transform;
   }

   // Example usage
   void Start() {
       AttacheModelToPrefab(ModelPrefab[Random.Range(0, ModelPrefab.Count)]);
   }
}
more ▼

answered Apr 03 '12 at 12:36 AM

nschrag gravatar image

nschrag
245 5 9 13

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1259

asked: Apr 02 '12 at 08:10 AM

Seen: 538 times

Last Updated: Apr 03 '12 at 12:36 AM