Unity - How can I dynamically swap the 3D model of a target

May 5, 2013 - 11:48am #1

This article explains how the 3D model of an Image target (or other trackable) can be swapped with a different 3D model at runtime, in Unity3D.

Steps:

  • create a Unity project and import the Image targets sample package; open the image targets scene
  • create a C# script, call it MyModelSwapper for instance
  • put the following code in the script:
using UnityEngine;
using System.Collections;

public class ModelSwapper : MonoBehaviour {
	
	public TrackableBehaviour theTrackable;
	
	private bool mSwapModel = false;
	
	
	// Use this for initialization
	void Start () {
		if (theTrackable == null)
		{
			Debug.Log ("Warning: Trackable not set !!");
		}
	}
	
	// Update is called once per frame
	void Update () {
		if (mSwapModel && theTrackable != null) {
			SwapModel();
			mSwapModel = false;
		}
	}
	
	void OnGUI() {
		if (GUI.Button (new Rect(50,50,120,40), "Swap Model")) {
			mSwapModel = true;
		}
	}
	
	private void SwapModel() {
		
		GameObject trackableGameObject = theTrackable.gameObject;
		
		//disable any pre-existing augmentation
		for (int i = 0; i < trackableGameObject.transform.GetChildCount(); i++) 
		{
			Transform child = trackableGameObject.transform.GetChild(i);
			child.gameObject.active = false;			
		}
		
		// Create a simple cube object 
		GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
		
		// Re-parent the cube as child of the trackable gameObject
		cube.transform.parent = theTrackable.transform;
	
		// Adjust the position and scale 
		// so that it fits nicely on the target
		cube.transform.localPosition = new Vector3(0,0.2f,0);
		cube.transform.localRotation = Quaternion.identity;
		cube.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
		
		// Make sure it is active
		cube.active = true;
	}
}
  • attach the script to the ARCamera object in your scene view
  • as you can see in the code, a public variable of type TrackableBehaviour, called theTrackable, is exposed;
  • in the inspector view, the MyModelSwapper script should expose a filed called "The Trackable"
  • drag one of the Image Targets from your scene view into the "The trackable" field of your script
  • save, build and run the app; a button labeled "Swap model" shpuld appear, by clicking it, the teapot of the target should be replaced with a simple cube

 

 

Topic locked