# How to detect the edge of a platform?

I have create a enemy AI script. These enemies are animals in my game. What I want is that the enemy can detect the edges of a platform.

using UnityEngine;
using System.Collections;

public class EnemyAI : MonoBehaviour {

public float walkSpeed = 2.0f;      // Walkspeed
public float wallLeft = 0.0f;       // Define wallLeft
public float wallRight = 5.0f;      // Define wallRight

float walkingDirection = 1.0f;
Vector2 walkAmount;

float originalY; // Original float value

void Start () {
this.originalY = this.transform.position.y;
}

// Update is called once per frame
void Update () {

walkAmount.x = walkingDirection * walkSpeed * Time.deltaTime;

if (walkingDirection > 0.0f && transform.position.x >= wallRight) {
walkingDirection = -1.0f;
Flip();
} else if (walkingDirection < 0.0f && transform.position.x <= wallLeft) {
walkingDirection = 1.0f;
Flip();
}

transform.Translate(walkAmount);
}

}


First of I store the original Y value inside a variable, so the object will be positioned on the platform I chose. Then in update it will do the walk animation.

Problem

I am now searching for a solution, so that the gameObject of enemy can detect the edges of the platform and turn away from it.

Looking out for some suggestions!

## 1 Answer

I would've added collider around the edges that will collide only with these characters' bodies. Then use OnCollisionEnter event (and maybe also check the tag of the colliding object) to turn around.

Could also use ray-casting... but I like the collider solution better. It's much more reliable.