CollisionBehavior component

We will now write a CollisionBehavior script to handle the collision events on the goal. In the Project Assets/ARBallPlay/Scripts/ folder, create a C# script named CollisionBehavior. Add the component to the GoalCollider object and then open it for editing. The full script is as follows:

File: CollisionBehavior.cs
using UnityEngine; using UnityEngine.Events; public class GameObjectEvent : UnityEvent<GameObject> { } public class CollisionBehavior : MonoBehaviour { public GameObjectEvent OnHitGameObject = new GameObjectEvent(); public UnityEvent OnCollision = new UnityEvent(); // used to make sure that only one event is called private GameObject lastCollision; void Awake() { //disables the renderer in playmode if it wasn't already MeshRenderer targetMeshRenderer = GetComponent<MeshRenderer>(); if (targetMeshRenderer != null) targetMeshRenderer.enabled = false; } void OnCollisionEnter(Collision collision) { if (lastCollision != collision.gameObject) { OnHitGameObject.Invoke(collision.gameObject); OnCollision.Invoke(); lastCollision = collision.gameObject; } } //So that the goal can be a trigger void OnTriggerEnter(Collider collider) { if (lastCollision != collider.gameObject) { OnHitGameObject.Invoke(collider.gameObject); OnCollision.Invoke(); lastCollision = collider.gameObject; } } public void ResetCollision() { lastCollision = null; }

void OnDisable() { lastCollision = null; }
}

In Awake() we just make sure the collider object won't be rendered. We already deleted the Renderer component from the object, so this won't do anything here, but just in case the developer forgets to remove or disable the renderer we take care of that.

The script implements handlers for OnCollisionEnter, OnTriggerEnter and OnDisable. It may seem redundant, but it's possible for Unity to trigger either OnCollisionEnger or OnTriggerEnter events (or both) for the same collision, we will handle both the same.

At the top of the script we define a new UnityEvent called GameObjectEvent. Our script will invoke the event on collisions so the UI and score keeper can respond to it.

The OnCollisionEnter and OnTriggerEnter functions are triggered by Unity physics. We check to make sure we don't already know about this goal and then invoke OnHitGameObject to notify the UI.

Save the script. Now we can implement the UI.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset