从Unity中的Gameobject []中选择一个脚本

时间:2016-12-05 23:38:17

标签: c# unity3d

我有一个我正在开发的游戏,它是一个TBS,并且会涉及许多生物。我想把我在运行时拥有的所有生物存储在一个数组中,我已经成功完成了。但是,我需要能够从这些数组项中调用所有脚本,因此:如何一次性在数组中的GameObjects上调用不同命名的脚本,或者我有什么替代方法?对于背景关于它的使用,请考虑D& D中的倡议。

1 个答案:

答案 0 :(得分:2)

假设您正在使用继承或接口,您可以创建基类/接口的数组,并将所有生物添加到该数组中(您说您拥有所有这些生物的数组)。

您只需循环遍历数组中的所有元素,然后调用相应的方法。

例如:

//not a cut-and-paste example, but gives you the general idea.
foreach(var _creature in Array)
{
   _creature.Die();
}

但是,如果您尝试为每个方法调用不同的方法,您可能会发现这对您不起作用。

如果你想进一步细分它,你可以尝试打开类型,然后为每种类型调用一个特定的方法,但它不是一个真正的通用类:

例如:

//not a cut-and-paste example, but gives you the general idea.
foreach(var _creature in Array)
{
   switch typeof(_creature):
      case LowLevel:
        _creature.Flee();
        break;
      case MidLevel:
        _creature.Guard();
        break;
      case HighLevel:
        _creature.Attack();
        break;
      default:
        _creature.Idle();
        break;
}

多态实现的一个例子:

public abstract class Combatant : MonoBehaviour
{
    //for arguments sake, we are only going to have speed property, attack method which
    //all instances have to implement, and a defend which only some might implement their
    //own method for (the rest default to the base class)
    int speed {get;set;}

    //Need to have this method in derived classes
    //We don't define a body, because the derived class needs to define it's own
    protected abstract void Attack();

    //Can be overriden in derived class, but if not, falls back to this implementation
    protected virtual void Defend()
    {
        speed *= 0.5; //half speed when defending
    }
}

public class MonsterA : Combatant
{
    protected override void Attack()
    {
        //attack code goes here for MonsterA
    }

    //to access speed, we simply need to use base.speed
    public void SomethingElse()
    {
        base.speed *= 1.25;
    }

    //notice we don't have to provide an implementation for Defend, but we can still access it by calling base.Defend(); - this will then run the base classes implementation of it.
}

public class MonsterB : Combatant
{
    protected override void Attack()
    {
        //attack code goes here for MonsterB
    }

    //Assume this is a 'heavier' class 'monster', speed will go down more than standard when defending
    protected override void Defend()
    {
        base.speed *= 0.3;
    }
}