- Home /
How to make a Character controller destroy an object?
Making a simple box game and the premiss is wandering around a world and destroying cubes by running into them. The problem I'm having is getting the cubes to register as being hit by the player and then destroying and adding to the score. I really don't know what code to use for this collision. I'm currently using a FPS character.
Answer by LoserKidKlazy · Feb 14, 2013 at 06:33 AM
You want to add a script to the block that look for collision with the player. Here is my code in C#
using UnityEngine;
using System.Collections;
public class DestroyScript : MonoBehaviour {
// Get the player, and his code
GameObject player;
PlayerScript playerScript;
// Use this for initialization
void Start () {
// find the player object
player = GameObject.Find("Player");
// gain access to this script
playerScript = player.GetComponent<PlayerScript>();
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider collider)
{
if(collider.gameObject.tag == "Player")
{
// destroy this object
Destroy(gameObject);
}
}
}
Answer by Arithan · Feb 14, 2013 at 06:33 AM
One way would be to attach the following script to the cubes:
function OnTriggerEnter(other : Collider)
{
if (other.gameObject.CompareTag("Player"))
{
// add your code to increase the score
Destroy(gameObject);
}
}
Make sure the cubes' colliders are triggers and the player has a "Player" tag. The if statement simply checks to see if the object that touched the cube is the player.
More details on collision can be found in the documentation:
Your answer
