Object Interactions
Interaction with other game objects
In computer games it is not enough to have only a character which can move. The character should also be able to interact with specific objects from the environment. For instance, let's say we need to collect some objects from the map. After, we collect them, they disappear. Let's see how you could implement this. 😃
1. Firstly, we need to make the 2 objects to be able to interact with other. For this, for both objects in scene we need to add a new component: Rigidbody. On Hierarchy, click on the object, then in Inspector menu click on Add Component. Type Rigidbody and select the component from the list.
2. For both objects deactivate gravity.
3. For the object we want to disappear when in collision with the other, check Is trigger option from Box Collider menu.
4. Create a new script for the object we want to disappear. Write the following code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectInteraction : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
Destroy(gameObject);
}
}
The Is trigger option you have previously checked allows us to write the function OnTriggerEnter, which receives as parameter the other GameObject. This function will be executed only when the two objects collide. Inside this function, in order
to destroy the object, we call the function Destroy().