2017-04-04 9 views
-2

私はゲームをしていて、現在は近接攻撃を受けています。私は敵を見つけるなどのすべてのコードを実行しましたが、今はその敵にダメージを与える必要があります。それで私の敵(Slime)curHealth intのスクリプトにアクセスする必要があるのです。ここでc#別のクラスからのアクセス方法

は近接武器のためのコードである:ここで

{ 
    private float meeleAttackStart = 0f; 
    private float meeleAttackCooldown = 0.5f; 
    public int meeleDamage = 40; 

    // Use this for initialization 
    void Start() 
    { 

    } 

    // Update is called once per frame 
    void Update() 
    { 
     if (Input.GetKeyDown(KeyCode.Mouse0) && Time.time > meeleAttackStart + meeleAttackCooldown) 
     { 
      RaycastHit2D[] hitArea = Physics2D.BoxCastAll(transform.position, Vector2.one, 0, Vector2.up); 
      if(hitArea != null) 
      { 
       for(int i = 0; i < hitArea.Length; i = i+1) 
       { 
        if(hitArea[i].collider.tag == "Enemy") 
        { 
         // do stuff 
        } 

       } 
      } 

      meeleAttackStart = Time.time; 
     }   
    } 
    ... 
} 

(いくつかのスウェーデン語の単語はそれについて心をいけないかもしれません)私の敵のために私のコードです(まだ進行中)

{ 
    public int maxSlimeHealth = 40; 
    public int curSlimeHealth = 40; 

    // Use this for initialization 
    void Start() 
    { 

    } 

    // Update is called once per frame 
    void Update() 
    { 

    } 
} 
+1

をあなたがヒットする敵を発見した場合、それは 'instanceOfThatEnemy.curSlimeHealthでなければなりません;' しかし、あなたはあなたがそれを見つけた部分を見せなかったので、私は確かに言うことができません。 –

+0

あなたがすでに試したことを示すことができればいいでしょう。 [尋ねる]を見てください。あなたは研究努力を示すべきです。あなたは[ColliderのAPI](https://docs.unity3d.com/ScriptReference/Collider.html)を見ましたか? ['gameObject'変数](https://docs.unity3d.com/ScriptReference/GameObject.html)を持っているのが分かりますが、これを何か別の方法で使ってみましたか?また、あなたの質問には本当の*質問*が含まれていません、私はどこにでも疑問符が表示されません。 – PJvG

答えて

2

簡単で悪い解決策はちょうど使用することですhitArea[i].collider.gameObject.GetComponent<TYPE_OF_YOUR_COMPONENT>().curSlimeHealth;
しかし、これをややエレガントな方法でやりたければ、私はインターフェイスを作ることを提案します。 IMortalまたは基底クラスCreatureBehaviourを呼び出し、そのインタフェース/抽象クラスのメソッドを呼び出します。あなたができる​​あなたhitArea[i].collider.tag"Enemy"ある場合

public class Slime 
    : CreatureBehaviour 
{ 

} 

そして、あなたは同様の方法でこれを使用することができますが、代わりのチェックや:

public class CreatureBehaviour 
    : MonoBehaviour 
{ 
    int m_Health = 40; 
    public int Health { get { return m_Health; } } 

    // you can add defense attribute 
    int m_Defense; 
    public int Defense { get { return m_Defense; } } 

    public void DoDamage(double atkPower) 
    { 
     // calculate this creature defence agains attack power 
     int damage = atkPower - this.Defense; 
     m_Health -= damage; 
     // check health and other stuff. 
    } 
} 

今すぐあなたのスライムの作成:例では、このようなものかもしれませんちょうどチェック:

var creature = hitAread[i].collider.gameObject.GetComponent<CreatureBehaviour>(); 
if (creature) 
    creature.DoDamage(13.37D); 
関連する問題