Log in
12
February

Move a GameObject with Collider

Written by DynamicHead. No comments Posted in: Professional
Tagged with , , , ,

The rule is simple: If you want to move a gameObject with a collider component attached you should also attach a rigidbody.

To test this yourself just create a new scene and add the following script to the camera and have a look at the Profiler at runtime.
(It needs some seconds to set up all the objects. Use the “Use Rigidbody” flag to de/attach a rigidbody to the moving cube. With “Grid Size” you can set the size of the static cube array.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using UnityEngine;
using System.Collections;
 
public class PerformanceTest : MonoBehaviour
{
	public bool m_UseRigidbody = false;
	public int m_GridSize = 150;
 
	private Vector3 m_Velo = new Vector3( 0f, -5f, 0f );
	private GameObject m_MovingCube;
 
	void Start ()
	{
		if( m_GridSize <= 0 )
			m_GridSize = 150;
 
		m_MovingCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
 
		this.transform.position = new Vector3( (m_GridSize / 2), (m_GridSize / 2), -20f);
		m_MovingCube.transform.position = new Vector3( (m_GridSize / 2), m_GridSize, -2f);
		m_MovingCube.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
 
		for (int i = 0; i < m_GridSize; i++)
		{
			for (int j = 0; j < m_GridSize; j++)
			{
				GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
				cube.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
				cube.transform.position = new Vector3(j, i, 0f);
			}
		}
 
		if( m_UseRigidbody )
		{
			m_MovingCube.AddComponent<Rigidbody>();
			m_MovingCube.rigidbody.useGravity = false;
			m_MovingCube.rigidbody.AddForce ( m_Velo, ForceMode.VelocityChange );
		}
	}
 
	void Update()
	{
		if( !m_UseRigidbody )
			m_MovingCube.transform.position += m_Velo * Time.deltaTime;
 
		this.transform.LookAt( m_MovingCube.transform );
	}
}