Question

I am making my first game in Unity 3D something like tower defense game. I have imported a Fbx model of a tower and attached it to a prefab. Now I want the nozzle of the tower to rotate and follow the enemy as the enemy passes by . In the fbx model i imported i got I have two poly meshes one for the base of the tower that is fixed, and one for the top of the tower that will rotate. Now I tried to create two different gameObject with these two meshes but if I put them on same point they overlap. So I have to do manual alignment such that the nozzle sit correctly over the base. I was wondering if there is any other way such that entire towers remain is one gameObject and I can rotate the upper part.

Was it helpful?

Solution

I did manage to solve my problem. Not sure if was the best way , but it works.

To upgrade the towers and transform only the nozzle part I essentially did this.

public class tryFbx : MonoBehaviour {
    public GameObject[] ModelPrefab;
    GameObject modelInstance;
    Renderer rn = new Renderer();

    // Attaching the model to prefab at runtime by creating a array of prefabs
    public void AttachModelToPrefab(GameObject modelPrefab) {
       modelInstance = GameObject.Instantiate(modelPrefab) as GameObject;
       modelInstance.transform.position = transform.position;
       modelInstance.transform.rotation = transform.rotation;

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

    void Start () {

    }

    // Update is called once per frame
    void Update () {
            if (GameManager.upgrade){
            AttachModelToPrefab(ModelPrefab[GameManager.towerUpgradeLevel]);
            foreach ( Renderer r in modelInstance.GetComponentsInChildren<Renderer>()){
                    // "polySurface98" is the name of the mesh I want to rotate. The tower and its upgrade have the same name.
                    if (r.name == "polySurface98") 
                    rn = r; 
             }
        // apply any transformation to the partial fbx
        rn.transform.Translate(1,1,1);
       }
    }
}

OTHER TIPS

You can create a hierarchy of GameObjects; you'll have one parent GameObject representing the tower and 2 children, being that you rotate one of them. Note that the coordinates of the children will be in relation to the parent's, so any "messy" manual calibration you make on the children will be contained.

Or, more complicated, you can create only one mesh that has an animation and apply it to one GameObject.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top