在 Unity 5 中,在 PlayerMovement 类的第 35 行使用 c# 时出现此错误:
错误 CS0120 非静态字段需要对象引用,
方法或属性“GameManager.completeLevel()”
玩家动作类别:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public GameObject deathParticals;
public float moveSpeed;
private Vector3 spawn;
// Use this for initialization
void Start () {
spawn = transform.position;
moveSpeed = 5f;
}
// Update is called once per frame
void Update() {
transform.Translate(moveSpeed * Input.GetAxis("Horizontal") * Time.deltaTime, 0f, moveSpeed * Input.GetAxis("Vertical") * Time.deltaTime);
if (transform.position.y < -2)
{
Die();
}
}
void OnCollisionStay(Collision other)
{
if (other.transform.tag == "Enemy")
{
Die();
}
}
void OnTriggerEnter(Collider other)
{
if (other.transform.tag == "Goal")
{
GameManager.completeLevel();
}
}
void Die()
{
Instantiate(deathParticals, transform.position, Quaternion.identity);
transform.position = spawn;
}
}
游戏管理器类:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
public static int currentScore;
public static int highscore;
public static int currentLevel = 0;
public static int unlockedLevel;
public void completeLevel()
{
currentLevel += 1;
Application.LoadLevel(currentLevel);
}
}
As your GameManager
类继承自MonoBehaviour
,此脚本需要附加到游戏对象。然后你需要获得对GameManager
组件,可以通过多种方式完成。
GameManager gameMananger = GameObject.Find("GameManager").GetComponent<GameManager>();
如果您的游戏对象名为“GameManager”,则上述内容将起作用,如果它被称为其他名称,请将其交换为您的对象的名称。
Then gameMananger.completeLevel();
现在可以工作了。
你可以将其缩短为GameObject.Find("GameManager").GetComponent<GameManager>().completeLevel();
如果 GameManager 脚本与 PlayerMovement 附加到同一游戏对象,这就是您所需要的GetComponent<GameManager>().completeLevel();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)