2016-10-23 6 views
0

두 번째 게임 개체에 첨부 된 다른 스크립트를 사용하여 게임 개체에 연결된 스크립트에서 함수를 호출하려고합니다.Unity의 다른 스크립트에서 함수 호출하기

플레이어, 게임 관리자라는 두 게임 개체가 호출됩니다.

플레이어 골드라는 스크립트를 가지고 있으며 게임 관리자 GameManager.cs에서 Gold.cs에) 기능을 SetGold을 (전화를 시도

GameManager

라는 스크립트를 가지고,하지만 난 오류가 점점 오전 : NullReferenceException이 : 개체 참조를하지 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)

객체

내 현재 코드의 istance로 설정

using UnityEngine; 
using System.Collections; 

public class GameManager : MonoBehaviour { 

    GameObject GO_Player; 
    Gold gold; 

    void Start() 
    { 
     GO_Player = GameObject.Find ("Player"); 
     gold = GO_Player.GetComponent<Gold>(); 
    } 

    void OnApplicationQuiot() 
    { 
     Save(); 
    } 
    public void Load() 
    { 
     gold.SetGold(PlayerPrefs.GetFloat("gold", 50)); 
    } 
    private void Save() 
    { 
     PlayerPrefs.SetFloat("gold", 1); 
    } 

    public void DeleteSaves() 
    { 
     PlayerPrefs.SetFloat("gold", 0); 
    } 
} 

미리 감사드립니다.

+0

'GameManager gm;에서'gm = new GameManager()'로 초기화하십시오; 'gold' 객체에 대해서도 같은 작업을하거나 새로운 GameManager() 대신에 생성자 – MethodMan

+0

을 생성하십시오; gm = gameObject.AddComponent를 사용해야했습니다. (); 재생을 눌렀을 때 몇 초에 같은 오류가 발생합니다. NullReferenceException : 개체 참조가 개체의 인스턴스로 설정되어 있지 않습니다. Gold.SetGoldDisplay (단일 금액) (Assets/Scripts/Player/\ –

+0

@MethodMan'MonoBehaviour'에서 상속받은 클래스에'new' kneyword를 사용할 수 없습니다. OPS의 현재 코드는 정상적으로 보입니다. – Programmer

답변

1

Awake에서 초기화 작업을 사용하는 것이 좋습니다 (1, 2, 3). 나는 여기에 응답 framgment 중 하나 인용하고있다 :

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 참조 예외가 나에게 모든 초기화는 시작에 기록 된 당신으로 초기화하기 전에 액세스하려고 생각합니다.

관련 문제