두 번째 게임 개체에 첨부 된 다른 스크립트를 사용하여 게임 개체에 연결된 스크립트에서 함수를 호출하려고합니다.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);
}
}
미리 감사드립니다.
'GameManager gm;에서'gm = new GameManager()'로 초기화하십시오; 'gold' 객체에 대해서도 같은 작업을하거나 새로운 GameManager() 대신에 생성자 – MethodMan
을 생성하십시오; gm = gameObject.AddComponent를 사용해야했습니다.(); 재생을 눌렀을 때 몇 초에 같은 오류가 발생합니다. NullReferenceException : 개체 참조가 개체의 인스턴스로 설정되어 있지 않습니다. Gold.SetGoldDisplay (단일 금액) (Assets/Scripts/Player/\ –
@MethodMan'MonoBehaviour'에서 상속받은 클래스에'new' kneyword를 사용할 수 없습니다. OPS의 현재 코드는 정상적으로 보입니다. – Programmer