Iteration with variable name [duplicate]

情到浓时终转凉″ 提交于 2020-06-02 17:06:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!