top of page
Search
Writer's pictureAbishek J Reuben

Creating a Exploded View for 3D Models in Unity


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,797 views4 comments

Recent Posts

See All

4 Comments


Martin Reimer
Martin Reimer
Jan 28, 2022

Awesome script! Thank you!

Like

pkaiser3d
Jan 25, 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

Like
Gopi Krishna Kattunga
Gopi Krishna Kattunga
Jun 12
Replying to

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

Like
bottom of page