C# Unity 5非静态字段、方法或属性错误需要对象引用
在Unity 5中,在我的PlayerMovement类的第35行使用c#时,我有以下错误: 错误CS0120非静态字段需要对象引用, 方法或属性“GameManager.completeLevel()” 玩家移动等级:C# Unity 5非静态字段、方法或属性错误需要对象引用,c#,class,oop,unity5,instantiation,C#,Class,Oop,Unity5,Instantiation,在Unity 5中,在我的PlayerMovement类的第35行使用c#时,我有以下错误: 错误CS0120非静态字段需要对象引用, 方法或属性“GameManager.completeLevel()” 玩家移动等级: using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public Ga
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;
}
}
您需要实例化GameManager对象
public GameObject gameManager;
Instantiate(gameManager)
或者正如Jim提到的:
您需要将completeLevel标记为静态:
更多信息请参见:
由于您的
GameManager
类继承自MonoBehavior
,因此需要将此脚本附加到游戏对象。然后您需要获得对GameManager
组件的引用,这可以通过多种方式完成
GameManager GameManager=GameObject.Find(“GameManager”).GetComponent()代码>
如果您的游戏对象名为“GameManager”,则上述操作有效。如果您的游戏对象名为其他对象,请将其替换为您的对象名
然后GameManager.completeLevel()代码>现在可以工作了
你可以把这个缩短到
GameObject.Find(“GameManager”).GetComponent().completeLevel()代码>
如果GameManager脚本附加到与PlayerMovement相同的游戏对象上,那么这就是您所需要的全部GetComponent().completeLevel()代码>var gm=new GameManager()在哪里?
public GameObject gameManager;
Instantiate(gameManager)
static public void completeLevel()
{
....
}