[英]access global game data in Unity (C#)
我對Unity和C#完全陌生。 我嘗試使用自己的OOP知識來構建一些東西,以容納游戲的數據和“業務邏輯”。
游戲概述:一些立方體掉落,可以在掉落時移動,最后放到窗格上。
多維數據集是預制的對象,必須進行跟蹤以計算分數,檢測不良行為等。
在場景中是:
GameMain.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class GameMain : MonoBehaviour
{
private float CubeSpawnSpeed = 3.0f; //seconds
private int score = 0;
// construtor
public GameMain()
{
}
// getter: is falling allowed for the cube
public bool getFalling(){
return true;
}
// getter cube spawn speed
public float getCubeSpawnSpeed(){
return this.CubeSpawnSpeed;
}
}
FallingScript必須從MainGame(獲取程序),FallingSpeed和下降許可中獲取數據。
CubeFalling.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoxFalling : MonoBehaviour
{
public GameMain gameMain;
void Start(){
// an attempt to get the instance this way, but fail
// GameMain main = GameObject.Find("GameMain").GetComponent<GameMain>();
}
void Update()
{
// Is still falling allowed?
if (gameMain.getFalling()){
transform.Translate(Vector3.down);
}
}
}
但這會產生錯誤NullReferenceException: Object reference not set to an instance of an object BoxFalling.Update ()
也不能通過將GameMain GameObject拉到CubeFalling腳本中的gameMain插槽到相同的命名公共變量來使用檢查器。
我一直期望的是,我必須將GameMain腳本拉到GameMain GameObject上,這等效於使用new GameMain
進行實例化。 為了重用此實例,我必須在下降腳本中將GameObject拉到GameMain變量。 但這不起作用。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class GameMain : MonoBehaviour
{ private static GameMain _gameMain;
public static GameMain Instance {get {return _gameMain;}}
void Awake()
{
_gameMain = this;
}
// getter: is falling allowed for the cube
public bool getFalling(){
return true;
}
}
BoxFalling.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoxFalling : MonoBehaviour
{
void Update()
{
// Is still falling allowed?
// now you can got it
if (GameMain.Instance.getFalling()){
transform.Translate(Vector3.down);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.