【发布时间】: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