我对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变量。但这不起作用。
答案 0 :(得分:4)
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);
}
}
}
答案 1 :(得分:0)
您可以使用Singleton访问GameMain
。将来在运行时实例化更多多维数据集时,这将很方便。
但是您也应该能够使用
来检索GameMain
gameMain = GameObject.Find("GameMain").getComponent<GameMain>();
也许您拼错了什么?找不到停用的对象。
(编辑:此方法搜索层次结构中的所有GameObject。至少缓存结果。有关更多信息,请访问Unity's documentation)