anyway to ensure that A gameobject dose not choose to move to a position if it was occupied by another ?
I'm using an Array of gameobject to designate points in the 3D world, and then i want an NPC gameobject to move to one of these points at random after reaching one of them, my problem is that I do not want the gameobject to choose one of these points as it finale destination if it was occupied by another point.
public class EnamyShipAI : MonoBehaviour {
public float moveSpeedforward;
GameObject[] movePointone = new GameObject[3];
// Use this for initialization
void Start () {
movePointOne = GameObject.FindGameObjectsWithTag("MovePoint");
}
//Update is called once per frame
void Update () {
transform.position = Vector3.MoveTowards(transform.position,
movePointOne[0].transform.position,
moveSpeedforward * Time.deltaTime);
}
}
I was thinking of before the moving gameObject, it will choose one point at random, mark it as occupied so other Instantiated objects cannot choose it, then move to it, a point dose not go back choosable till the occupied object has moved.
but i'm not sure where to start to coding that idea.
Answer by Dibbie · Jun 20, 2016 at 04:03 PM
You could do an "occupied" idea.
In a separate script, you would just have 1 public variable called "occupied", essentially: public bool occupied;
Then, for example reasons, lets say you had called that script "PointChecker", so in your main script here, in update, you would do something like: //create a temp variable to store a random number based on the size of the "point" array int loc = Random.Range(0, movePointone.Length - 1);
//Check if occupied
if(movePointone[loc].GetComponent<PointChecker>().occupied == false){
//move to location
transform.position = Vector3.MoveTowards(transform.position,
movePointOne[loc].transform.position,
moveSpeedforward * Time.deltaTime);
//Set this spot to "occupied"
movePointone[loc].GetComponent<PointChecker>().occupied == true
}
(C#, untested code)
Another way you could do it is checking if that spot has a child, so it would be something like: //create a temp variable to store a random number based on the size of the "point" array int loc = Random.Range(0, movePointone.Length - 1);
//Check if occupied by parents, children
if(movePointone[loc].transform.childCount == 0){
//move to location
transform.position = Vector3.MoveTowards(transform.position,
movePointOne[loc].transform.position,
moveSpeedforward * Time.deltaTime);
//Set this spot to "occupied"
transform.parent = movePointone[loc].transform;
}
(C#, untested code)
Thanks, that exactly what I wanted, i was going to trying to do it all in one single script, but your way is way more easier