Collision scripting.

Hi, I want to make a Java script code for when my 1st person character collides with a cube it destroys it. None of the coding/scripting or tutorials I have found have actually worked, and some have actually caused more problems! when someone writes gameobject in an example script are they expecting me to replace it with ‘cube’?.

Does my 1st person character need to have a mesh collider? does it need to be a trigger?

Does the cube need to be a trigger, rigid body?

I really need help with this, as everything I’ve been told just causes errors!

Thanks for any help :slight_smile:

If someone types ‘gameObject’ it is always the object the script is attached to, whereas ‘GameObject’ is a reference type ( a class).
gameObject is an instance of the type GameObject.

I did my best to write a simple code in JS for you, i usually never use JS though and hope it works fine for you.
Dont forget to set the tag of the objects you want to destroy to “Cube” (or any other tag as long as you change it in the script).

This only works if you also use a CharacterController component on your players gameobject, if you want to do the same with rigidbodys, it’s quite similar although the movement should rather be done in FixedUpdate instead of Update.

var charController : CharacterController;

function Awake()
{
	// get a reference to your characterController component so that you can access its methods and attributs
	charController = gameObject.GetComponent(CharacterController);
}

function Update()
{
	// here comes your control-logic for the character, for a simple test we'll just move it 1 unit/second
	charController.Move(Vector3.forward*Time.deltaTime);
}

function OnControllerColliderHit(other : ControllerColliderHit)
{
	// only destroys gameobjects that have the tag "Cube"
	// don't forget to set it in the inspector of the object that you want to destroy
	if(other.gameObject.tag == "Cube")
	{
		Destroy(other.gameObject);
	}
}