【问题标题】:how to use one function of a script in another script in unity using c#如何使用c#在另一个脚本中统一使用脚本的一个功能
【发布时间】:2015-03-28 04:22:54
【问题描述】:

我正在用 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 条件下从 playercontroller 脚本调用 BulletCount 函数到 BulletDestroy 脚本

【问题讨论】:

  • playerController.BulletCount();
  • 在 BulletDestroy 的 onStart 中必须写 playerController = GetComponent();除非你在编辑器中设置它。
  • 我试过了,但它说对象引用未设置为对象的实例
  • @Ogen:关于您的已关闭问题,这再次意味着您遇到了 XY 问题——您正在尝试解决 错误 问题。告诉我们您的问题域,而不是您尝试解决它的方式,我们可以为您提供帮助。或者你可以删除你的问题,然后我们不能。浪费我的呼吸,我可以看到....
  • @HovercraftFullOfEels 这是错误的问题,这就是我删除它的原因。感谢您的跟进。

标签: c# function object unity3d reference


【解决方案1】:

如果不了解所有 C# 程序,您可以使用高效的 C# 方式或推荐给初学者的 Mono 方式。

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

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

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# 的主要核心之一。仅供参考,您只能继承一次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    相关资源
    最近更新 更多