top of page

Creating a Exploded View for 3D Models in Unity

  • Writer: Abishek J Reuben
    Abishek J Reuben
  • Nov 22, 2018
  • 1 min read

Had to create an Exploded view for 3D models for a VR/AR 3D model viewer I was working on. As first instinct I googled to see if someone has made it already for Unity, and sadly left empty handed. So I decided to make one for myself, and it came out pretty well I think.





The Code :


//Coded by Abishek J Reuben


using UnityEngine;

using System.Collections.Generic;

using System;


[Serializable]

public class SubMeshes

{

public MeshRenderer meshRenderer;

public Vector3 originalPosition;

public Vector3 explodedPosition;

}


public class ThreeDModelFunctions : MonoBehaviour

{

#region Variables


public List<SubMeshes> childMeshRenderers;

bool isInExplodedView = false;

public float explosionSpeed = 0.1f;

bool isMoving = false;



#region UnityFunctions


private void Awake()

{

childMeshRenderers = new List<SubMeshes>();


foreach (var item in GetComponentsInChildren<MeshRenderer>())

{

SubMeshes mesh = new SubMeshes();

mesh.meshRenderer = item;

mesh.originalPosition = item.transform.position;

mesh.explodedPosition = item.bounds.center * 1.5f;

childMeshRenderers.Add(mesh);

}

}


private void Update()

{

if (isMoving)

{

if (isInExplodedView)

{

foreach (var item in childMeshRenderers)

{

item.meshRenderer.transform.position = Vector3.Lerp(item.meshRenderer.transform.position, item.explodedPosition, explosionSpeed);


if (Vector3.Distance(item.meshRenderer.transform.position, item.explodedPosition) < 0.001f)

{

isMoving = false;

}

}

}

else

{

foreach (var item in childMeshRenderers)

{

item.meshRenderer.transform.position = Vector3.Lerp(item.meshRenderer.transform.position, item.originalPosition, explosionSpeed);


if (Vector3.Distance(item.meshRenderer.transform.position, item.originalPosition) < 0.001f)

{

isMoving = false;

}

}

}

}

}



#region CustomFunctions


public void ToggleExplodedView()

{

if (isInExplodedView)

{

isInExplodedView = false;

isMoving = true;

}

else

{

isInExplodedView = true;

isMoving = true;

}

}


}

 
 
 

4 comentarios


Martin Reimer
Martin Reimer
28 ene 2022

Awesome script! Thank you!

Me gusta

pkaiser3d
25 ene 2022

Hi, thank you for your awesome script. Could you give some hints about applying the script on a model. Where we should attach the script? How to wire to a button and what is the requirement for the exploded model (pivot) etc.? Thank you in advance. Peter from Hungary

Me gusta
Gopi Krishna Kattunga
Gopi Krishna Kattunga
12 jun 2024
Contestando a

which object you want explode attach the script call the function ToggleExplodedView()

Me gusta
bottom of page