问题
Is it possible to make iteration from variables in c#?
i have variables public Transform dest1, dest2, dest3, dest4,...
and public StudentScript stu1, stu2, stu3, stu4, ...;
and what i want is if collide with student1 then agent go to dest1 and callscript from stu1, if student2 then dest2 and stu2...
if (Physics.Raycast (ray, out hit)) {
if (hit.collider.name == "_student1") {
Debug.Log (hit.transform.name);
agent.SetDestination (dest1.position);
if (Mathf.Abs (tagent.position.x - dest1.position.x) <= closeEnough && Mathf.Abs (tagent.position.z - dest1.position.z) <= closeEnough) {
stu1.ResetStudentBehaviour();
}
}else if (hit.collider.name == "_student2") {
agent.SetDestination (dest2.position);
if (Mathf.Abs (tagent.position.x - dest2.position.x) <= closeEnough && Mathf.Abs (tagent.position.z - dest2.position.z) <= closeEnough) {
stu2.ResetStudentBehaviour();
}
}else if (hit.collider.tag == "_student3") {
...
sorry for asking this beginner-like question
回答1:
Yes. The feature you want is called an "array". An array is a collection of variables that is indexed by an integer position.
public Transform[] destinations = new Transform[10];
...
destinations[0] = whatever;
whatever = destinations[9];
and so on.
来源:https://stackoverflow.com/questions/37393173/iteration-with-variable-name