如何使用c#在另一个脚本中统一使用脚本的一个函数

时间:2015-03-28 04:22:55

标签: c# function object unity3d reference

我与c#团结一致 我想在另一个脚本中使用脚本的功能

第一个脚本名称播放器控制器

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

public Vector2 moving = new Vector2();
public int Bulletlimit = 0;
public int MaxBulletlimit = 3;

public Bullet bullet;
// Use this for initialization
void Start () {

}

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

    moving.x = moving.y = 0;

    if (Input.GetKey ("right")) {
        moving.x = 1;
    } else if (Input.GetKey ("left")) {
        moving.x = -1;
    }

    if (Input.GetKey ("up")) {
        moving.y = 1;
    } else if (Input.GetKey ("down")) {
        moving.y = -1;
    }


    if (Input.GetKey ("s")) {

        BulletShot();   
}   

}

public void BulletShot(){
    if(Bulletlimit < MaxBulletlimit)
    {
        Bullet clone = Instantiate (bullet, transform.position, Quaternion.identity) as Bullet;
        Bulletlimit = Bulletlimit + 1;
    }
}


public void BulletCount()
{
    Bulletlimit = Bulletlimit - 1;
}
}

第二个脚本名称Bullet Destroy

using UnityEngine;
using System.Collections;


public class BulletDestroy : MonoBehaviour {

private Player player;
private PlayerController playerController;

// Use this for initialization
void Start () {

}

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

}

public void OnTriggerEnter2D(Collider2D target){
    if (target.gameObject.tag == "Deadly") {
        Destroy (gameObject);
    }

}

public void OnCollisionEnter2D(Collision2D target){
    if (target.gameObject.tag == "Deadly") {
        Destroy (gameObject);
        }
}
}

如何在if条件中将bulletCount函数从playercontroller脚本调用到BulletDestroy脚本

1 个答案:

答案 0 :(得分:0)

如果他们不了解所有C#程序,您可以使用高效的C#方式或建议初学者使用的Mono Way。

第一是从另一个类继承。我不会讨论,因为如果你不知道它是如何运作的,将来可能会给你一些问题。

第二个是通过从播放器获取组件。如果在您的游戏中,播放器被标记为播放器,那么让我们使用该引用。或者至少是Player GameObject的名称。

PlayerController myCharactersScript;
void Start(){
     myCharactersScript = GameObject.Find("myCharactersName").GetComponent<PlayersController>();


}

public void OnTriggerEnter2D(Collider2D target){
if (target.gameObject.tag == "Deadly") {
    Destroy (gameObject);
   myCharactersScript.BulletCount();
}

}

我建议您阅读有关继承的良好编码实践,因为它是C#的主要核心之一。仅供参考,你只能继承一次。