2016-10-23 96 views
0

2番目のゲームオブジェクトにアタッチされている他のスクリプトを使用して、ゲームオブジェクトにアタッチされているスクリプトから関数を呼び出そうとしています。Unityの他のスクリプトから関数を呼び出す

Player、Game Managerという2つのゲームオブジェクトが呼び出されます。

プレーヤーは、ゴールドと呼ばれるスクリプトを持っており、ゲームマネージャがGameManager

がGameManager.csからGold.csでSetGold()関数を呼び出すようにしようと、私はエラーを取得していますと呼ばれるスクリプトがありますいないオブジェクト参照:とNullReferenceExceptionをオブジェクトのistanceに設定

私の現在のコード: Gold.cs:

using UnityEngine; 
using System.Collections; 

public class Gold : MonoBehaviour { 
    GameManager gm; 

    public UnityEngine.UI.Text goldDisplay; 

    private float _gold; 

    void Start() 
    { 
     gm = GameObject.Find("Game Manager").GetComponent<GameManager>(); 
     gm.Load(); 
    } 

    void Update() 
    { 
     UpdateGoldDisplay(); 
    } 

    public void SetGold(float x) 
    { 
     _gold = x; 
    } 

    public float GetGold() 
    { 
     return _gold; 
    } 

    public void UpdateGoldDisplay() 
    { 
     SetGoldDisplay(GetGold().ToString()); 
    } 
    public void SetGoldDisplay(string x) 
    { 
     goldDisplay.text = x; 
    } 
} 

私の他のスクリプト(GameManager.cs)

​​3210

ありがとうございました。

+0

'GameManager gm;'を 'gm = new GameManager()'に初期化します。 'gold'オブジェクトに対しても同じことをするか、新しいGameManager()の代わりにコンストラクタ – MethodMan

+0

を作成します。私はgm = gameObject.AddComponentを使用しなければならなかった(); Playを押すと何らかの理由で、同じエラーが2番目に多く発生する:NullReferenceException:オブジェクト参照がオブジェクトのインスタンスに設定されていない Gold.SetGoldDisplay(単額)(Assets/Scripts/Player/\ –

+0

@MethodMan 'MonoBehaviour'から継承したクラスで' new' kneywordを使用することはできません。 OPSの現在のコードは正常に見えます。 – Programmer

答えて

1

初期化作業をAwakeで使用することをお勧めします(詳細は123)。 は、私がここに回答framgmentの1を引用しています:

Usually Awake() is used to initialize if certain values or script are dependent of each other and would cause errors if one of them is initialized too late (awake runs before the game starts). Awake is also called only once for every script instance.

あなたのnull参照の例外が、私はあなたがまたスタートで書かれたあなたのすべての初期化と初期化の前にそれにアクセスしようとしていることを考えさせます。

関連する問題