hi,i want to check when a player is inside an area. This is my script.Help me!
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class deathtime : MonoBehaviour {
private int health;
public Text healthText;
// Use this for initialization
void Start () {
health = 1000;
}
// Update is called once per frame
void Update () {
healthText.text = "Health: " + health;
//if game object is inside the area
health = health - 1;
}
}
Create a gameObject and assign it a collider. Make that collider a trigger and use “OnTriggerEnter” in your methods.
Create a bounding box from script via the bounds class and assign it a size. Check with that bounds object whether a point is inside of that bounding box (Bounds.Contains()).
There are more approaches which might be better suited. That’s hard to say though since you were not really specific on the “area” as LeftyRighty said.
Maybe you can check the distance between the vector3 of the object and the vector3 of the area ? and if it’s distance is less than 3 for example then the player is inside the area ?
// at the top of the Script put:
public GameObject PlayerObject;
//now put this function anywhere in the script
bool GetPlayerInsideArea(float Distance)
{
bool PlayerInArea = false;
if(!PlayerObject)
{
PlayerObject = GameObject.FindGameObjectWithTag("Player");
}
if(Vector3.Distance(PlayerObject.transform.position,new Vector3(3,2,2)) < Distance || Vector3.Distance(PlayerObject.transform.position,new Vector3(3,2,2)) == Distance)
{
PlayerInArea = true;
}
return PlayerInArea;
}
Now you can call it in update like that:
void Update () {
if(GetPlayerInsideArea(3f))
{
healthText.text = "Health: " + health;
//if game object is inside the area
health = health - 1;
}
}
you can change 3 to the maximum distance the player allowed to go far…
public GameObject characterObject;
public GameObject areaObject;
public float areaLength = 0; // distance between characterObject and areaObject
bool GetEnemyInsideArea()
{
if (Vector3.Distance(player.transform.position, areaObject.transform.position) <= areaLength) // if distance between areaObject and character equal or less return true otherwise false
return true;
return false;
}